SpringBoot响应自定义异常消息并且自动识别客户端与浏览器做出不同响应
使用 @ControllerAdvice 注解和 @ExceptionHandler 注解将异常捕获后直接返回数据。(这时候是没有自适应效果,浏览器还是客户端请求错误都是返回JSON形式数据)
@ControllerAdvice
public class MyExceptionHandler {
// 浏览器客户端返回的都是json
@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 ,SpringBoot会使用BasicErrorController来接管错误请求然后去响应,这时候已经是自适应的错误响应。
@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",e.getMessage());
//转发到/error
return "forward:/error";
}
将自己定制的数据携带出去
因为返回的数据中都是通过BasicErrorAttributes.getErrorAttributes方法来获取model数据,这个方法是DefaultErrorAttribute中的方法。所以想要返回自定义的数据直接手写DefaultErrorAttribute类即可。
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
}
ErrorMvcAutoConfigration中默认会注入DefaultErrorAttributes,如果自己手写一个ErrorAttributes(这是一个接口)然后放入容器中则可以让SpringBoot在获取model数据时从自定义的ErrorAttributes中获取
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes();
}
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
map.put("company","atguigu");
//我们的异常处理器携带的数据
Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
map.put("ext",ext);
return map;
}
}