首先定义一个异常
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
当在control类中throw此异常
@Controller
public class HelloController {
@RequestMapping("/json")
public String json() throws MyException {
throw new MyException("发生错误2");
}
}
处理该异常
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = MyException.class) //这个注解,接受异常
@ResponseBody //返回json
public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
ErrorInfo<String> r = new ErrorInfo<>();
r.setMessage(e.getMessage());
r.setCode(ErrorInfo.ERROR);
r.setData("Some Data");
r.setUrl(req.getRequestURL().toString());
return r;
}
}
应用启动:响应
{
code: 100,
data: "Some Data",
message: "发生错误2",
url: "http://localhost:8080/json"
}