使用Spring Boot在rest api服务中删除try catch并使用异常处理程序处理异常

问题描述 投票:0回答:1

只想处理 API 的异常处理程序类的异常。有什么办法可以去掉API的所有try-catch吗

使用@exceptionhandler,但这种方法没有解决目的。有没有什么方法不需要try catch?

java spring spring-boot exception exceptionhandler
1个回答
0
投票

当然,您所需要的只是一个顶部有

@ControllerAdvice
注释的类,并扩展
ResponseEntityExceptionHandler
例如:

@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {
    // just for the example but you should probably handle specific exceptions rather than handle 'Exception.class'
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> processError(Exception exception) {
        // do something with the exception
        return new ResponseEntity<>("Oups", INTERNAL_SERVER_ERROR);
    }
    ...
}

当然你需要删除

try-catch
或重新抛出异常

© www.soinside.com 2019 - 2024. All rights reserved.