简体   繁体   English

@ExceptionHandler(Exception.class)不处理所有类型的异常

[英]@ExceptionHandler(Exception.class) not handling all types of exceptions

I am trying to handle all Types of exceptions using @ExceptionHandler(Exception.class) . 我试图使用@ExceptionHandler(Exception.class)处理所有类型的异常。 But it's not handling all types of exception. 但它并没有处理所有类型的异常。

When I am trying to access wrong HTTP method from postman/ browser I am not getting any response blank page is coming. 当我试图从邮递员/浏览器访问错误的HTTP方法时,我没有得到任何响应空白页面即将到来。

Can please any one tell me why I am not getting any response or tell me if I am doing something wrong in my code? 可以请任何人告诉我为什么我没有得到任何回复或告诉我,如果我在我的代码中做错了什么?

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {


        @ExceptionHandler(Exception.class)
        public ResponseEntity<ExceptionMessage> handleAllExceptionMethod(Exception ex,WebRequest requset,HttpServletResponse res) {


            ExceptionMessage exceptionMessageObj = new ExceptionMessage();

            exceptionMessageObj.setStatus(res.getStatus());
            exceptionMessageObj.setError(ex.getLocalizedMessage());     
            exceptionMessageObj.setException(ex.getClass().getCanonicalName());
            exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());  

            return new ResponseEntity<ExceptionMessage>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);          
        } 

Either override ResponseEntityExceptionHandler#handleExceptionInternal() or don't extend ResponseEntityExceptionHandler . 要么覆盖ResponseEntityExceptionHandler#handleExceptionInternal()要么不要扩展ResponseEntityExceptionHandler

@Order(Ordered.HIGHEST_PRECEDENCE) on a @ControllerAdvice should work before ResponseEntityExceptionHandler is invoked as per this answer which suggests that Spring Framework 4.3.7 is needed. @ControllerAdvice上的@Order(Ordered.HIGHEST_PRECEDENCE)应该在根据这个答案调用ResponseEntityExceptionHandler之前工作,这表明需要Spring Framework 4.3.7。

This will handle the exceptions raised from within the controller method. 这将处理从控制器方法中引发的异常。

If you send a request for which there is no mapping the controller method will not be invoked at all thus the @ExceptionHandler will be obsolete in that case. 如果发送没有映射的请求,则根本不会调用控制器方法,因此在这种情况下@ExceptionHandler将会过时。

Maybe this article on creating custom handlers may help: article 也许这篇关于创建自定义处理程序的文章可能会有所帮助

Using RequestMapping you can create different responses for every Http code. 使用RequestMapping,您可以为每个Http代码创建不同的响应。 In this example I show how to control errors and give a response accordingly. 在这个例子中,我展示了如何控制错误并相应地给出响应。

This is the RestController with the service specification 这是具有服务规范的RestController

@RestController
public class User {

    @RequestMapping(value="/myapp/user/{id}", method = RequestMethod.GET)
    public ResponseEntity<String> getId(@PathVariable int id){

        if(id>10)
            throw new UserNotFoundException("User not found");

        return ResponseEntity.ok("" + id);
    }

    @ExceptionHandler({UserNotFoundException.class})
    public ResponseEntity<ErrorResponse> notFound(UserNotFoundException ex){

        return new ResponseEntity<ErrorResponse>(
            new ErrorResponse(ex.getMessage(), 404, "The user was not found") , HttpStatus.NOT_FOUND);
    }
}

Within the getId method there is a little logic, if the customerId < 10 It should response the Customer Id as part of the body message but an Exception should be thrown when the customer is bigger than 10 in this case the service should response with an ErrorResponse. 在getId方法中有一点逻辑,如果customerId <10它应该响应客户ID作为正文消息的一部分但是当客户大于10时应该抛出异常,在这种情况下服务应该响应ErrorResponse 。

public class ErrorResponse {

    private String message;
    private int code;
    private String moreInfo;

    public ErrorResponse(String message, int code, String moreInfo) {
        super();
        this.message = message;
        this.code = code;
        this.moreInfo = moreInfo;
    }

    public String getMessage() {

        return message;
    }

    public int getCode() {

        return code;
    }

    public String getMoreInfo() {

        return moreInfo;
    }
}

And finally I'm using an specific Exception for a "Not Found" error 最后我使用了一个特定的Exception来查找“Not Found”错误

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring @ExceptionHandler(Exception.class)总是被调用。 为什么? - Spring @ExceptionHandler(Exception.class) always gets called. Why? 为什么 @ExceptionHandler(MethodArgumentNotValidException.class) 被忽略而支持 @ExceptionHandler(Exception.class) - Why @ExceptionHandler(MethodArgumentNotValidException.class) is ignored in favour of @ExceptionHandler(Exception.class) 使用 @ControllerAdvice 注释 @ExceptionHandler(Exception.class) 工作但 @ExceptionHandler({AuthenticationException.class) 不工作 - Using @ControllerAdvice annotation @ExceptionHandler(Exception.class) is working but @ExceptionHandler({AuthenticationException.class) is not working 如何确保 @ExceptionHandler(Exception.class) 在 Spring Boot 中最后被调用? - How to make sure that @ExceptionHandler(Exception.class) will be called last in Spring Boot? 期望Exception.class的TestNG类 - TestNG classes expecting Exception.class 使用JUnit @Test(expected = Exception.Class)捕获异常 - Catching Exception with JUnit @Test(expected=Exception.Class) Mockito:thenThrow(Exception.class)和thenThrow(new Exception())之间的区别 - Mockito: difference between thenThrow(Exception.class) and thenThrow(new Exception()) 两个daoimpl类的@Transactional(rollbackfor = Exception.class) - @Transactional(rollbackfor=Exception.class) for two daoimpl class 如何对捕获Exception.class的方法进行单元测试? - How to make a unit test for a method that is catching Exception.class? @Transactional(rollbackFor = {Exception.class})不回滚事务 - @Transactional(rollbackFor={Exception.class}) does not rollback transaction
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM