spring boot 老版本处理异常 对于浏览器客户端,返回error数据
对于非浏览器返回json数据, 主要取决于你的请求head 是什么
但是当我们自定义了: 老版本无论请求什么都会返回json异常数据,
@ControllerAdvice
public class UserExceptionHandler {
@ResponseBody
@ExceptionHandler(UserNotFoundExits.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 ,客户端返回json
@RequestMapping(
produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request); // 此处做了更改
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity(status);
} else {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity(body, status);
}
}
|