springboot 全局异常处理
程序员文章站
2022-05-03 10:24:11
...
1.定义一个controller 编写两个方法一个用于抛出页面异常,另外一个用于抛出json异常
@Controller
public class HelloController {
@Autowired
private BlogProperties blogProperties;
@RequestMapping("/test")
public String hello() throws Exception{
System.out.println("=============exception:"+blogProperties.getName());
throw new Exception("发生错误");
}
@RequestMapping("/json")
public String json()throws MyException {
throw new MyException("发生错误2");
}
}
2.定义myException 并且编写全局异常处理类
public class MyException extends Exception{
public MyException(String message) {
super(message);
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(value=Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e)throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName(DEFAULT_ERROR_VIEW);
return modelAndView;
}
@ExceptionHandler(value = MyException.class)
@ResponseBody
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;
}
}
public class ErrorInfo<T> {
public static final Integer OK = 0;
public static final Integer ERROR = 100;
private Integer code;
private String message;
private String url;
private T data;
}
测试页面: