尝试设置一个全局自定义异常处理机制,该机制依赖于可以处理异常的@RestControllerAdvice。
@RestControllerAdvice**异常处理程序根本不触发。在这里,我使用的是低级客户端。
我设置了以下控制器建议,以返回错误条件的API约定:
我试着在下面添加
@ExceptionHandler(value = { ResponseException.class })
public ApiErrorResponse noHandlerFoundException(Exception ex) {
LOG.error(ex.getCause().toString());
int status = ((ResponseException) ex).getResponse().getStatusLine().getStatusCode();
return new ApiErrorResponse(status, "<some message depending on status code>");
}但是看到了同样的结果
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>GlobalControllerExceptionHandler:
@RestControllerAdvice
public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler{
private static final Logger LOG = Logger.getLogger(GlobalControllerExceptionHandler.class);
@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiErrorResponse constraintViolationException(ConstraintViolationException ex) {
LOG.error(ex.getCause().toString());
return new ApiErrorResponse(400, "Bad Request");
}
@ExceptionHandler(value = { NoHandlerFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiErrorResponse noHandlerFoundException(Exception ex) {
LOG.error(ex.getCause().toString());
return new ApiErrorResponse(404, "Resource Not Found");
}
@ExceptionHandler(value = { Exception.class })
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiErrorResponse unknownException(Exception ex) {
LOG.error(ex.getCause().toString());
return new ApiErrorResponse(500, "Internal Server Error");
}
}ApiErrorResponse:
public class ApiErrorResponse {
private int status;
private String message;
public ApiErrorResponse(int status, String message) {
this.status = status;
this.message = message;
}
public int getStatus() {
return status;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return new ToStringBuilder(this).append(status)
.append(message)
.toString();
}
}这样做的问题是当我使用第三方库做一些事情时。
发布于 2019-03-24 22:12:40
确保正在扫描您的控制器建议。
为此,您可以将控制器建议类放在spring boot应用程序主类的内部包中,以便spring boot将自动扫描所有内部包。
或
尝试向您的配置类添加@EnableWebMvc注释。
发布于 2020-11-15 17:19:07
这是因为您试图通过javax.validation.ConstraintViolationException;处理嵌套异常,ConstraintViolationException是org.springframework.transaction.TransactionSystemException;的嵌套异常
将处理程序更改为@ExceptionHandler(TransactionSystemException.class)
TransactionSystemException不是一个理想的解决方案,但它是有效的。在Spring Boot版本的最新版本:>= 2.4.0中修复了此错误
在下面的链接中,您可以看到他们如何解包ConstraintViolationException
Unwrap ConstraintViolationException from TransactionSystemException
或者,您可以升级到:
// Gradle Config
plugins {
id 'org.springframework.boot' version '2.4.0'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}从Spring Boot版本:>= 2.4.0开始,您现在可以处理嵌套异常。
https://stackoverflow.com/questions/55324610
复制相似问题