我在spring rest应用程序中使用了一个全局异常处理程序,我想隐藏jdbc异常,但是它不能按预期工作。我关闭了数据库以强制执行连接异常,然后在日志中看到以下异常,并且收到了默认的spring错误响应,但没有收到我在异常处理程序中定义的响应
java.lang.IllegalStateException: Could not resolve parameter [1] in public org.springframework.http.ResponseEntity<java.lang.Object> ...
throws java.io.IOException: No suitable resolver
这是代码。
@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({JDBCConnectionException.class})
public ResponseEntity<Object> dbError(JDBCConnectionException exception,
HttpHeaders headers,
HttpStatus status,
WebRequest request) throws IOException
{
Map<String,Object> body = new HashMap<>();
body.put("errorId",Long.valueOf(201));
body.put("state",HttpStatus.SERVICE_UNAVAILABLE.value());
body.put("message", "internal failure");
body.put("time", new Date().toString());
return new ResponseEntity<>(body, headers, status);
}
希望你能帮助我。
答案 0 :(得分:0)
正如注释所暗示的那样,@ControllerAdvice
被用作REST端点上的扩展,这些异常处理程序将处理 REST API 的异常,并且不影响其在日志记录中的记录方式。安慰。相反,它将确定如何将异常报告给最终用户,并允许您编写简洁的错误消息而不会泄漏有关程序的信息。
如果您想完全捕获一个异常,而不仅仅是REST API,请查看this blog。
但是,我不建议您这样做,因为这将极大地减少您作为开发人员可以使用的信息,最终用户无法看到此信息,因此REST API自定义异常应该提供足够的抽象。
希望对您有帮助。
答案 1 :(得分:0)
我发现失败了……对于那种异常,spring无法解析这两个参数。
HttpHeaders headers,
HttpStatus status
很明显,提到的参数[1]例外。
java.lang.IllegalStateException: Could not resolve parameter [1] in public org.springframework.http.ResponseEntity<java.lang.Object> ...
throws java.io.IOException: No suitable resolver
我删除了这两个参数,并且异常处理程序处理了异常。
此代码现在有效
@ExceptionHandler(JDBCConnectionException.class)
public ResponseEntity<Object> dbError(Exception ex,
WebRequest request)
{
Map<String,Object> body = new HashMap<>();
body.put("errorId",Long.valueOf(201));
body.put("state",HttpStatus.SERVICE_UNAVAILABLE.value());
body.put("message", "internal failure");
body.put("time", new Date().toString());
return new ResponseEntity<Object>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}