[英]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.