1. Anomaly classification
Java exceptions are divided into two categories: "check" and "non-check". The word "check" means that when the code is compiled, the compiler will check whether there is any exception handling (catching or throwing up). For exceptions classified as needing to be checked, if they are not processed, the compilation will not be able to be passed.
When I was beginners, I often wonder why exceptions should be handled in this way? Later I understood a little, there are only two types of abnormalities: subjective and objective. One can be avoided in most cases and the other cannot be avoided in most cases.
Exceptions like NullPointerException are mostly linked to programmers' qualities (well developed and tested, they will basically not pop up after the system is run). They can basically be avoided. The Java syntax used them to class as "non-check exceptions", which also saved programmers and compilers a lot of trouble;
Exceptions related to external environments such as IOException are almost inevitable (the network will hang up one day and the other). However, when encountering unexpectedly, the program still needs to make a difference, so the compiler needs to urge the programmer to check and see if these possible unexpected exceptions have been handled. When the Exception object is passed to a node, the program can perform some measures, such as: returning a prompt to the user ("The system is busy, please try again"), pushing an exception message to the monitoring platform, etc.
2. Unified return processing of exceptions
1. Container processing
The following lists the processing methods of Tomcat, configure them under web.xml, and handle them according to http return code or Exception type:
<error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> <error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/views/error/throwable.jsp</location> </error-page>
Disadvantages: Cannot handle requests that do not need to return html, such as ajax;
2. Framework processing
The following lists the processing methods of Spring MVC
(1) Use the SimpleMappingExceptionResolver, the simple exception handler included in Spring MVC;
(2) Implement the interface HandlerExceptionResolver custom exception handler; (It is recommended to use it, and can support ajax and other extensions)
(3) Use the @ExceptionHandler annotation to implement exception handling;
Type (1), configure under spring-mvc.xml
<!-- Go to the exception thrown by the Controller to a specific view --> <bean> <property name="exceptionMappings"> <props> <!-- Different exceptions jump separately-> <!-- You can customize different exceptions--> <prop key="com.test.MyException1">/error/e1</prop> <prop key="com.test.MyException2">/error/e2</prop> <!-- If you don't want to customize exceptions, just configure the following --> <prop key="java.lang.Throwable">/error/500</prop> </props> </property> </bean>
Disadvantages: Cannot handle requests that do not need to return html;
Type (2), the implementation class of custom HandlerExceptionResolver interface
/** * Custom exception handler: supports ajax * @author wangxu * */public class MyExceptionHandler implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { /* Differentiate ajax */ boolean isAjax = request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request .getHeader("X-Requested-With").toString()); if (!isAjax) { if (ex instanceof com.test.MyException1) { return new ModelAndView("/error/e1"); } else if (ex instanceof com.test.MyException1) { return new ModelAndView("/error/e2"); } else { return new ModelAndView("/error/500"); } } String jsonRes = "{/"message/":/"" + "System Exception" + "/"}";// Custom structure and foreground docking PrintWriter out = null; try { out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setContentType("text/plain;charset=utf-8"); out.print(jsonRes); out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } return null; }}And register the processor under spring-mvc.xml
<bean id="exceptionHandler"/>
Advantages: It can handle ajax requests, and it is also convenient for encoding to implement functional extensions, such as exception monitoring, etc.
Type (3), @ExceptionHandler annotation
@Controllerpublic class TestExceptionHandlerController { @ExceptionHandler({ MyException1.class }) public String exception(MyException1 e) { return "/error/e1"; } @RequestMapping("/mary") public void test() { throw new MyException1("No money!"); }}Disadvantages: The method of @ExceptionHandler must be under the same Controller as the method of possible throwing exceptions. (Not recommended)
3. Combination
In actual projects, when handling uniform returns of exceptions, some custom exceptions or extensions will be handed over to the framework, and the mapping of the http return code will be handed over to the container, because the http return code is more outer, some cannot reach the framework, and some are not an exception to the framework (such as 404 and Spring MVC). The framework runs in the container. When the framework takes the exception first and returns it, the container will no longer be mapped.
The above is all about this article, I hope it will be helpful to everyone's learning.