使用 spring 引导的自定义异常句柄
Custom exception handle with spring boot
在这里,我的要求是我想在我的应用程序中使用单独的代码来处理异常,我看到 spring 的一个不错的选择,使用@controller 建议来全局处理异常。
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
但是我想在那里自定义,比如适当的动态消息,自己的错误代码。那么我该怎么做,我是 spring 引导的新手,甚至我都不了解 spring.Need 基本示例。
你可以像这样想出一个 class 来捕获异常情况下要发送的响应信息:-
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;
}
}
在你的控制器建议中class:-
- return 键入 APIResponse 而不是 void。
- 处理程序方法可以将引发的异常作为参数。
- 使用异常对象创建 APIResponse 对象。
- 将@ResponseBody 放在处理程序方法上。
在这里,我的要求是我想在我的应用程序中使用单独的代码来处理异常,我看到 spring 的一个不错的选择,使用@controller 建议来全局处理异常。
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
但是我想在那里自定义,比如适当的动态消息,自己的错误代码。那么我该怎么做,我是 spring 引导的新手,甚至我都不了解 spring.Need 基本示例。
你可以像这样想出一个 class 来捕获异常情况下要发送的响应信息:-
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;
}
}
在你的控制器建议中class:-
- return 键入 APIResponse 而不是 void。
- 处理程序方法可以将引发的异常作为参数。
- 使用异常对象创建 APIResponse 对象。
- 将@ResponseBody 放在处理程序方法上。