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

use*_*581 11 java rest spring spring-mvc

美好的一天,

我正在做春季休息api,我想确保一切正常.我想记录异常行为,如nullPointerException或数据库连接错误或任何可能引发或未处理或未假设的异常.

我想捕获任何未处理的异常并向用户显示漂亮的消息,而不是打印堆栈跟踪.

为此我在互联网上找到了一个扩展ResponseEntityExceptionHandler并覆盖handleExceptionInternal方法的解决方案.

我还想记录404错误,看看是否有人试图攻击我的服务器.

我还在属性文件中添加了这一行:spring.mvc.throw-exception-if-no-handler-found = true

这是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);

}
Run Code Online (Sandbox Code Playgroud)

我的问题是当我传递错误的路由像/ abc这个代码运行正常,但是当我从控制器方法抛出空指针异常时,这个方法没有捕获它.

谢谢.

Bog*_*ros 8

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

ControllerAdvice-没有其他属性,它将处理所有异常,因此可以提供意外的行为。最好为basePackages属性提供一个包(您的包),并且只处理指定包中引发的异常。

最好将Exceptions与自定义@ExceptionHandler标记的方法分开,这将使处理程序逻辑分离。