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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48508285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:52:09  来源:igfitidea点击:

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

javaspringrestspring-mvc

提问by user3454581

Good day,

再会,

I am working on spring rest api and i would like to sure everything is working fine. 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.

我正在研究 spring rest api,我想确保一切正常。我想记录异常行为,如 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.

谢谢。

采纳答案by Bogdan Oros

@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();
    }
}

ExceptionHandlerDocumenation - here you can find all objects the method signature can operate with.

ExceptionHandler文档 - 在这里您可以找到方法签名可以操作的所有对象。

ControllerAdvice- with no additional properties it will handle all exceptions, so it can provide unexpected behavior. It's better to provide a package (your package) to basePackagesproperty and it will handle only exceptions thrown in specified package.

ControllerAdvice- 没有额外的属性,它将处理所有异常,因此它可以提供意外的行为。最好为basePackages属性提供一个包(你的包),它只会处理指定包中抛出的异常。

Also it is a good practice to separate Exceptions to custom @ExceptionHandlermarked methods, it will decouple the handlers logic.

此外,将异常与自定义@ExceptionHandler标记的方法分开也是一种很好的做法,它将分离处理程序逻辑。