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

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

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

@ControllerAdvice
@RestController
public 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
save_snippets.png

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

猜你喜欢

转载自blog.csdn.net/vcstrong/article/details/70159062