Spring MVC将异常映射到HTTP状态码

来源:互联网 发布:树莓派python编程实战 编辑:程序博客网 时间:2024/05/16 03:31

在自定义的异常类上使用@ResponseStatus更改当请求产生异常时返回的HTTP状态码时产生了问题,虽然异常仍然被@ExceptionHandler注解的异常处理方法拦截了,但是产生的状态码仍然是200。

解决方法是将@ResponseStatus注解移到异常处理方法上,如

@ControllerAdvice@RestControllerpublic class CustomExceptionHandler {    @ExceptionHandler(UserNotFoundException.class)    @ResponseStatus(HttpStatus.NOT_FOUND)    public Map<String, String> emptyResultHandler() {        Map<String, String> map = new HashMap<String, String>();        map.put("status", "error");        map.put("message", "用户名或密码错误!");        return map;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

此时就可以得到404的状态码。不过产生问题的原因未知。

0 0