【问题标题】:Custom exception handle with spring boot带弹簧靴的自定义异常句柄
【发布时间】:2015-05-14 06:19:52
【问题描述】:
在这里,我的要求是我希望在我的应用程序中使用单独的代码来处理异常,我看到了一个不错的 spring 选项,它使用@controller 建议来全局处理异常。
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
但是我想在那里自定义,比如正确的动态消息,自己的错误代码。那么我该怎么做呢,我是 Spring Boot 新手,甚至我也不了解 Spring。需要基本示例。
【问题讨论】:
标签:
java
spring
spring-mvc
spring-boot
【解决方案1】:
你可以想出一个像这样的类来捕获在异常情况下发送的信息:-
public class APIResponse {
int errorCode;
String description;
String someInformation;
// any other information that you want to send back in case of exception.
}
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ResponseBody
@ExceptionHandler(DataIntegrityViolationException.class)
public APIResponse handleConflict(DataIntegrityViolationException exception) {
APIResponse response = createResponseFromException(exception);
return response;
}
}
在您的控制器建议类中:-
- 返回类型为 APIResponse 而不是 void。
- 处理程序方法可以将引发的异常作为参数。
- 使用异常对象创建 APIResponse 对象。
- 将@ResponseBody 放在处理程序方法上。