Sping 4 exception handling and sping Exception Handling
Ing between exceptions and HTTP status codes (@ ResponseStatus)
By default, Spring automatically maps the exceptions thrown by itself to the appropriate status code, as shown in the following examples:
For example, if the backend throws the following exception (TypeMismatchException, the type does not match when passing parameters to the method ):
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "2l" at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:77) at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47) at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:603)...
The frontend returns status code 400:
In addition to the above exceptions, for other exceptions and exceptions thrown by our business, if the Http status code is not explicitly bound, the response will contain 500 status code by default.
Of course, in addition to these default mechanisms, we can also use the @ ResponseStatus annotation to customize the Http status code of the exception binding feature, as shown in the following example:
Define an exception and bind the 400 status code through the @ ResponseStatus annotation:
@ResponseStatus(value = HttpStatus.NOT_FOUND)public class MyException extends RuntimeException{}
Then the controller throws the custom exception throw new MyException ();
Access the controller and find that the response returns a 400 status code.
Exception Handling Method in the Controller (@ ExceptionHandler)
Exception Handling MethodIn the same controllerThe exception thrown by all methods is as follows:
We added a MyException exception handling method under the controller and directly returned it to the body.
@ExceptionHandler(MyException.class) @ResponseBody public String handleException(){ return "handle by ExceptionHandler."; }
Open the browser and observe the results:
Controller notification (@ ControllerAdvice)
The exception handling method can only handle exceptions thrown by the same controller. However, a system must have more than one controller. It is impossible to add a repetitive Exception Handling Method to each controller ~~
So how to handle exceptions for multiple controllers? Use the @ ControllerAdvice annotation.
Classes with @ ControllerAdvice annotations can receive exceptions thrown by all controllers in the system, as shown in the following example:
@ ControllerAdvicepublic class DSSExceptionHandler extends BaseController {/*** handle exceptions thrown by the controller ** @ return */@ ExceptionHandler (Exception. class) @ ResponseBody public String handleException (HttpServletRequest request, Exception e) {logger. error ("Request FAILD, URL = {}", request. getRequestURI (); logger. error (e. toString (), e); return gson. toJson (BaseController. FAILD);}/*** handle the exception thrown by the controller ** @ return */@ ExceptionHandler (NumberFormatException. class) @ ResponseBody public String handleNumberFormatException (HttpServletRequest request, NumberFormatException e) {logger. error ("Request FAILD, URL = {}", request. getRequestURI (); logger. error (e. toString (), e); return gson. toJson (BaseController. FAILD );}}
Note that this bean should be included during spring scan configuration. My configuration is as follows. For details, refer:
Spring-mvc.xml:
<context:component-scan base-package="com.cetiti.epdc.dss" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
Spring. xml
<context:component-scan base-package="com.cetiti.epdc.dss"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan>
In addition, in the preceding example, the handleNumberFormatException method is called because the exception has a smaller range and a higher priority.
References
Spring in action 4