44.SpringBoot学习笔记–定制错误数据
定制错误 JSON 数据
Exception
demo.yangxu.springboot.exception.UserNotExistException
package demo.yangxu.springboot.exception;
public class UserNotExistException extends RuntimeException {
public UserNotExistException() {
super("用户不存在");
}
}
Controller
demo.yangxu.springboot.controller.HelloController
package demo.yangxu.springboot.controller;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String Hello(@RequestParam("user") String user){
if(user.equals("aaa")){
throw new UserNotExistException();
}
return "Hello World";
}
}
demo.yangxu.springboot.controller.MyExceptionHandler
方式一:自定义异常处理与返回定制 JSON 数据
没有自适应效果,无论是浏览器还是非浏览器访问,都会返回 JSON 数据。
package demo.yangxu.springboot.controller;
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handleException(Exception e){
Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
方式二:转发到 /error 进行自适应响应效果处理
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message","用户出错啦");
request.setAttribute("ext",map);
//转发到/error
return "forward:/error";
}
Component
方式三:携带定制数据
出现错误以后,会来到 /error 请求,会被 BasicErrorController 处理,响应后获取的数据是由getErrorAttributes 返回的(org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController(org.springframework.boot.web.servlet.error.ErrorController)规定的方法)。
思路:
1、编写一个 ErrorController 的实现类(复杂),或者编写 AbstractErrorController 的子类(也复杂),放在容器中;
2、页面上或者返回 JSON 能用的数据都是通过 errorAttributes.getErrorAttributes [org.springframework.boot.web.servlet.error.ErrorAttributes#getErrorAttributes(org.springframework.web.context.request.WebRequest, org.springframework.boot.web.error.ErrorAttributeOptions)] 得到。容器中DefaultErrorAttributes.getErrorAttributes() [org.springframework.boot.web.servlet.error.DefaultErrorAttributes#getErrorAttributes(org.springframework.web.context.request.WebRequest, org.springframework.boot.web.error.ErrorAttributeOptions)] 默认进行数据处理的;
自定义 ErrorAttributes
demo.yangxu.springboot.component.MyErrorAttributes
package demo.yangxu.springboot.component;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.Map;
//给容器中加入自定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
map.put("blog","yangxu");
//异常处理器携带的数据
Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0);
map.put("ext",ext);
return map;
}
}
demo.yangxu.springboot.controller.MyExceptionHandler#handleException
request.setAttribute("ext",map);
最终效果
响应是自适应的,可以通过定制 ErrorAttributes 改变需要返回的内容。
可以尝试使用浏览器和非浏览器访问以下网址测试效果:
http://localhost:8080/crud/hello?user=aaa
使用浏览器访问返回错误信息:
status: 500
timestamp: Tue Jun 16 08:19:07 CST 2020
error: Internal Server Error
ext code: user.notexist
ext message: 用户出错啦
使用非浏览器访问返回 JSON 错误信息:
{
"timestamp": "2020-06-16T00:19:30.126+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/crud/hello",
"blog": "yangxu",
"ext": {
"code": "user.notexist",
"message": "用户出错啦"
}
}
参考
org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getStatus
protected HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
try {
return HttpStatus.valueOf(statusCode);
}
catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
javax.servlet.RequestDispatcher#ERROR_STATUS_CODE
String ERROR_STATUS_CODE = "javax.servlet.error.status_code";
webRequest.getAttribute(String name, int scope) 方法中要传入的 scope 参数:
org.springframework.web.context.request.RequestAttributes
/**
* Constant that indicates request scope.
*/
int SCOPE_REQUEST = 0;
/**
* Constant that indicates session scope.
* <p>This preferably refers to a locally isolated session, if such
* a distinction is available.
* Else, it simply refers to the common session.
*/
int SCOPE_SESSION = 1;