简体   繁体   English

如何处理spring rest API上的内部服务器错误(500)?

[英]How to handle Internal server error (500) on spring rest API?

Good day, 美好的一天,

I am working on spring rest api and i would like to sure everything is working fine. 我正在做春季休息api,我想确保一切正常。 I would like to log abnormal behaviors like nullPointerException or database connection error or any Exception that could raise and not handled or not assumed. 我想记录异常行为,如nullPointerException或数据库连接错误或任何可能引发和未处理或未假设的异常。

I would like to catch any unhandled exception and show a beautifull message to user instead of printing stack trace. 我想捕获任何未处理的异常并向用户显示漂亮的消息,而不是打印堆栈跟踪。

for this i found a solution on internet that is extend ResponseEntityExceptionHandler and override handleExceptionInternal method. 为此我在互联网上找到了一个扩展ResponseEntityExceptionHandler并覆盖handleExceptionInternal方法的解决方案。

I also like to log 404 errors to see if someone trying to attack on my server. 我还想记录404错误,看看是否有人试图攻击我的服务器。

I have also added this line in properties file : spring.mvc.throw-exception-if-no-handler-found=true 我还在属性文件中添加了这一行:spring.mvc.throw-exception-if-no-handler-found = true

and here is the code for handleExceptionInternal 这是handleExceptionInternal的代码

@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {

    GenericResponse response = new GenericResponse();
    response.setMessage("Internal error occured, " + ex.getStackTrace()[0]);

    System.out.println("big exceptions");

    return new ResponseEntity(response, headers, status);

}

My problem is when i am passing incorrect route like /abc this code is running fine, But when i throw null pointer exception from controllers method this method is not catching it. 我的问题是当我传递错误的路由像/ abc这个代码运行正常,但是当我从控制器方法抛出空指针异常时,这个方法没有捕获它。

thanks. 谢谢。

@ControllerAdvice
public class Handler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handle(Exception ex, 
                HttpServletRequest request, HttpServletResponse response) {
        if (ex instanceof NullPointerException) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

ExceptionHandler Documenation - here you can find all objects the method signature can operate with. ExceptionHandler Documenation - 在这里您可以找到方法签名可以使用的所有对象。

ControllerAdvice - with no additional properties it will handle all exceptions, so it can provide unexpected behavior. ControllerAdvice - 没有其他属性,它将处理所有异常,因此它可以提供意外行为。 It's better to provide a package (your package) to basePackages property and it will handle only exceptions thrown in specified package. 最好为basePackages属性提供一个包(你的包), basePackages处理在指定包中抛出的异常。

Also it is a good practice to separate Exceptions to custom @ExceptionHandler marked methods, it will decouple the handlers logic. 同样,将Exceptions与自定义@ExceptionHandler标记的方法分开是一个好习惯,它将解耦处理程序逻辑。

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

相关问题 Spring Data Rest执行查询,但返回500内部服务器错误 - Spring Data Rest executes query but returns 500 internal Server Error 异常处理 Rest API 作为内部服务器错误 (500) - Exception Handling Rest API as Internal Server Error(500) Spring Boot Post API 中的 500 内部服务器错误 - 500 Internal Server Error in spring boot post API 500 Internal Server Error球衣架 - 500 Internal Server Error jersey rest Spring 5 - HTTP 状态 500 – 内部服务器错误 - Spring 5 - HTTP Status 500 – Internal Server Error 尝试使用邮递员上的 put 和 post 方法到我的 spring 休息应用程序时出现 500 内部服务器错误 - Getting 500 internal server error when trying to use the put and post methods on postman to my spring rest app 在 Rest API 调用上使用 @Consumes 注释给出 500 Internal Server Error - Using @Consumes annotation on Rest API call giving 500 Internal Server Error 内部服务器错误(500)贝宝在沙箱中使用Java json有效负载创建付款Rest API - Internal Server Error(500) paypal create payment Rest API with Java json payload in Sandbox REST Jersey服务器JAX-RS 500内部服务器错误 - REST Jersey server JAX-RS 500 Internal Server Error 如何修复 spring 引导中的 500 内部错误 - How to fix 500 internal error in spring boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM