spring boot对404处理结果
-
浏览器请求结果
-
Postman请求结果
先看一下源码BasicErrorController
@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 ? new ModelAndView("error", model) : modelAndView;
}
@RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = this.getStatus(request);
return new ResponseEntity(body, status);
}
- 这两个方法分别对应着刚才的两种请求,我们可以知道造成这种不同的原因是http请求的header中的
Accept
是不是有text/html
所以对于异常的处理,我们也应该分成两个方面来进行处理
1.对于Accept
拥有text/html
的处理
在resources/resources/error目录下新建响应的错误页面
-
修改完后的效果
2.对其他形式访问的处理
/**
* @Auther: guaidan
* @Date: 2018/10/9 14:41
* @Description:
*/
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String,Object> handleUserNotFindException(UserNotFoundException ex){
Map<String,Object> result = new HashMap<>();
result.put("id",ex.getId());
result.put("msg",ex.getMessage());
return result;
}
}
响应结果
网友评论