代码之家  ›  专栏  ›  技术社区  ›  SpringUser

例如,getClass().getCanonicalName()不提供异常类名

  •  0
  • SpringUser  · 技术社区  · 8 年前

    我正在尝试处理Spring引导中的异常 @ControllerAdvice . 我正在处理所有类型的异常,使用 Exception.class 并给出JSON响应。

    当我添加 HTTPStatus status 在里面 handleAllExceptionMethod() 我收到以下回复时 null pointer exception is occurs

    但在那个JSON响应中,我期待 "error" : "java.lang.NullPointerException" 我从服务班扔的 throw new NullPointerException("Null values are not allowed")

    添加前 httpstatus状态 在里面 handleAllExceptionMethod()。 我得到了预期的结果。我在获取状态值的方法中添加了 status 提出。

    有人能告诉我为什么会这样吗?

    @ControllerAdvice
    public class RestExceptionHandler {
    
        @ExceptionHandler(Exception.class)
        public ResponseEntity<Object> handleAllExceptionMethod(Exception ex,WebRequest requset,HttpStatus status) {
    
            ExceptionMessage exceptionMessageObj = new ExceptionMessage();
    
            exceptionMessageObj.setStatus(status.value());
            exceptionMessageObj.setMessage(ex.getLocalizedMessage());
            exceptionMessageObj.setError(ex.getClass().getCanonicalName());     
            exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());
    
            return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(),status);     
        }
    }
    

    当我得到空指针异常时,这是JSON结果

    enter image description here

    0 回复  |  直到 8 年前