I. Classification of anomalies
Java exceptions are classified as "checking" and "non-checking". The word "checking" means that when code is compiled, the compiler will go to Check to see if there is exception handling (capture or throw up). For exceptions classified as checked, if not handled, compilation will not pass.
When I was a beginner, I often wondered why I should classify and deal with the abnormalities in this way. Later it became clear that there are only two kinds of anomalies: subjective and objective, one can be avoided in most cases, and the other can not be avoided in most cases.
Exceptions like NullPointerException are mostly linked to programmer quality (well developed, test OK, basically won't jump out after the system runs), basically can be avoided, java grammar originally classified them as "non-checked exceptions", but also saved programmers and compilers a lot of work.
Exceptions such as IOException, which are related to the external environment, are almost inevitable, but when they happen, the program still has to do something, so the compiler needs to urge the programmer to Check whether these 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 ("system is busy, please try again"), pushing an exception message to the monitoring platform, and so on.
2. Unified Return Processing of Exceptions
1. Container handling
The following lists Tomcat's processing methods, which are configured under web.xml and processed 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-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>
Disadvantage: unable to handle requests that do not need to return html, such as ajax;
2. Framework Processing
Here's how Spring MVC is handled
- Simple Mapping Exception Resolver with Spring MVC
- Implementing interface Handler Exception Resolver Custom exception handler; (Recommended to use, can support extensions such as ajax)
- Implementing exception handling with @ExceptionHandler annotation
Type (1) In the ____________ spring - Configuration under mvc.xml
<! - Transfer the exception thrown by Controller to a specific view - > <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <! - Different anomalies 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 the exception, configure the following <prop key="java.lang.Throwable">/error/500</prop> </props> </property> </bean>
Disadvantage: Unable to handle requests that do not need to return html
(2) Implementing class of custom Handler Exception Resolver interface
/**
* Custom exception handlers: support for ajax
* @author tangqing
*
*/
public class MyExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
/* Distinguish 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 Front 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;
}
}
Register the processor under spring-mvc.xml
<bean id="exceptionHandler" class="com.test.MyExceptionHandler"/>
Advantages: It can handle ajax requests, and also facilitate coding to achieve functional extensions, such as exception monitoring.
The @ExceptionHandler annotation
@Controller public class TestExceptionHandlerController {
@ExceptionHandler({
MyException1.class
}) public String exception(MyException1 e) {
return "/error/e1";
}@RequestMapping("/marry") public void test() {
throw new MyException1("No money!");
}
}
Disadvantage: The @ExceptionHandler method must be in the same Controller as the method that might throw an exception. (Not recommended)
3, combine
In practical projects, when handling uniform returns of exceptions, some custom exceptions or extensions will be handed over to the framework, and the mapping of http return codes will be handed over to the container, because http return codes are more outer, some can not reach the framework, and some are not exceptions to the framework (such as 404 and Spring MVC). The framework runs in the container. When the framework gets the exception first and handles it back, the container will no longer map.