@javazjm
2017-10-30T10:59:43.000000Z
字数 2616
阅读 2988
Springboot
异常
SpringBoot内置了一个BasicErrorController对异常进行统一的处理,当在页面发生异常的时候会自动把请求转到/error(Spring Boot提供的一个默认的映射)
,可以自定义页面内容,只需在classpath路径下新建error页面即可。当然我们也可以自定义error页面的路径
如:
server.error.path=/custom/error
BasicErrorController提供两种返回错误一种是页面返回、当你是页面请求的时候就会返回页面,另外一种是json请求的时候就会返回json错误
可以查看源码。
/**
* 统一异常处理
* Created by admin on 2017/8/7.
*/
@ControllerAdvice
public class MyExceptionHandler {
/**
* 异常处理, 返回视图
*
* @param req
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
/**
* 异常处理,返回自定义的异常对象json
*
* @param req
* @param e
* @return
* @throws Exception
*/
@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;
}
@ModelAttribute
public Model newUser(Model model) {
System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model");
model.addAttribute("user", "hong");
return model;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器");
}
}
public class ErrorInfo<T> {
public static final Integer OK = 0;
public static final Integer ERROR = 500;
private Integer code;
private String message;
private String url;
private T data;
public static Integer getERROR() {
return ERROR;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public class MyException extends Exception{
public MyException(String message) {
super(message);
}
}
路径:src/main/resources/templates/error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
请求地址:
<span th:text="${url}"></span>
<p>发生了异常...</p>
</body>
</html>
参考:didi