1 Introduction
Consistent exception handling for the importance of the application of self-evident. Today we introduce Spring how to unify the Rest exception handling. At the same time we will simply compare the advantages and disadvantages between them.
2. @Controller combined @ExceptionHandler
A controller in the method declaration and then @ExceptionHandler
a comment tag can be:
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/err")
@ResponseBody
public Object demo1(){
int i = 1 / 0;
return new Date();
}
@ExceptionHandler({RuntimeException.class})
public ModelAndView fix(Exception ex){
System.out.println(ex.getMessage());
return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
}
}复制代码
advantage:
- The highest priority.
@ExceptionHandler
Marking method supports multiple return type. May be a view, it can bejson
like.
Disadvantages:
- A
Controller
The@ExceptionHandler
exception type on the notes can not appear the same, otherwise throw a runtime exception. - Need to explicitly declare the type of exception processing.
- The scope is just
Controller
not global in the true sense abnormal. If it is to act on the global need to put all the parent controller.
3. @ControllerAdvice combined @ExceptionHandler
This is 2. improved, by defining @ControllerAdvice
and mark the class method @ExceptionHandler
to achieve the purpose of the global exception handler:
@ControllerAdvice
public class TestController {
@ExceptionHandler({RuntimeException.class})
public ModelAndView fix(Exception ex){
System.out.println(ex.getMessage());
return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
}
}复制代码
advantage:
- Global exception handling.
- Full body control response status code, and
- A plurality of abnormality mapped to the same method to deal with, and it makes full use of the updated Restful ResponseEntity response
Disadvantages:
- A
Controller
The@ExceptionHandler
exception type on the notes can not appear the same, otherwise throw a runtime exception. - Need to explicitly declare the type of exception processing.
Under normal circumstances also recommend using this mode exception handling. In most cases it is compatible.
4. HandlerExceptionResolver Interface
Implement HandlerExceptionResolver
interfaces, here we have inherited its abstract realization AbstractHandlerExceptionResolver
:
@Component
public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {
@Override
protected ModelAndView doResolveException(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
try {
if (ex instanceof IllegalArgumentException) {
return handleIllegalArgument((IllegalArgumentException) ex, response, handler);
}
//todo more exception
} catch (Exception handlerException) {
//todo
}
return null;
}
private ModelAndView
handleIllegalArgument(IllegalArgumentException ex, HttpServletResponse response)
throws IOException {
response.sendError(HttpServletResponse.SC_CONFLICT);
String accept = request.getHeader(HttpHeaders.ACCEPT);
//todo more response
return new ModelAndView();
}
}复制代码
advantage:
- This is a global exception handler.
- In this way global exception handler returns
JSP
,velocity
such as template view more convenient. - It supports a variety of response formats, although the method override returns
ModelAndView
but because there are parametersHttpServletResponse
, we can use it to customize the response results. For example, if a client asks forapplication / json
, so when an error occurs, we want to ensure that we return to aapplication / json
coded response.
Disadvantages:
- We need to lower the
HttpServletResponse
realization of various forms of response body to interact. - Low priority
5. Spring Boot exception handling
If you are using a framework is the Spring the Boot . We can also use its unique approach. The advantage is a low-level shield the API, disadvantages are also evident, can not capture the specific exception.
5.1 achieve ErrorController
Spring Boot by default, provides a /error
mapping to handle all errors in Servlet registered global error pages (containers WhiteLabel Error Page ) and returned to the client. By implementing ErrorController interfaces and registered as Bean . For example no longer here. You can refer to BasicErrorController
.
Add 5.2 ErrorAttributes
We can also add ErrorAttributes type of Bean to replace replace the default exception handling.
@Component
public class MyCustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(
WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes =
super.getErrorAttributes(webRequest, includeStackTrace);
errorAttributes.put("locale", webRequest.getLocale()
.toString());
errorAttributes.remove("error");
//todo your business
return errorAttributes;
}
}复制代码
5.3 inherits the base class BasicErrorController
Spring Boot automatic configuration provides an example implementation ErrorController base interface exception handling BasicErrorController , default processing text / html wrong type of request, the base class may inherit more custom processing request types, and the method used to add a common @RequestMapping annotations the produce attribute type specifying process.
@Component
public class MyErrorController extends BasicErrorController {
public MyErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes, new ErrorProperties());
}
@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Map<String, Object>> xmlError(HttpServletRequest request) {
//todo your business
}
}复制代码
6. Spring 5 的 ResponseStatusException
Also in the latest Spring 5 you can also throw ResponseStatusException
to handle exceptions.
benefit:
- More convenient to use
- Type, more status codes: type of exception can cause a variety of different responses. Compared with @ExceptionHandler, which reduces the tight coupling
- We will not have to create as many custom exception class
- Because you can create an exception programmatically, so you can better control exception handling
Disadvantages:
- There is no uniform way of handling exception, to enforce certain application-wide agreement even more difficult
- There may be a lot of duplication of code.
7. Summary
We commonly used unusual Spring way to handle exceptions were analyzed and summarized on the merits. I believe you can find the treatment that is right for you. If you like a spot of useful please help, your encouragement, my motivation!
关注公众号:Felordcn获取更多资讯