First, preface
How is an exception in the background so friendly and efficient that it echoes back to the front? Simply throwing a bunch of error messages to the user interface is obviously inappropriate.
Regardless of the implementation of the code, we hope so:
(1) If it is a page jump request, there is an exception, we would like to jump to an exception display page, as follows:
Of course, the interface here is not beautiful, but the theory is like this.
(2) If it is an AJAX request, then we would like the background to return a reasonable error display to the AJAX callback function, as follows:
$.ajax ({type:"POST"Url:"<%=request.getcontextpath ()%>"+"/businessexception.json", data: {}, DataType:"JSON", ContentType:"Application/json", Success: function(data) {if(Data.success = =false) {alert (data.errormsg); }Else{Alert ("Request succeeded without exception"); } },Error: function(data) {Alert ("The call failed ...."); }});
Print out the data.errormsg of the callback function:
Now, let's take a look at the implementation of the code based on the above ideas. Therefore, the example of this article contains the exception of custom sub-assembly, in order to read the following, please ape friends to see the blogger's another article: Java exception Encapsulation (own definition error code and description, with source).
Second, detailed examples
This example uses the Environment Eclipse+maven, where Maven is simply to facilitate the introduction of JAR packages.
Technology used: SPRINGMVC
In spring MVC, the Handlerexceptionresolver interface is implemented for all classes that handle exceptions thrown during request mapping and request processing. Handlerexceptionresolver interface has a method resolveexception, when the controller layer occurs after the exception will be entered into this method resolveexception.
Below we directly implement the Handlerexceptionresolver interface, the code is as follows:
Packagecom. Luo. Exceptionresolver;Import Java. IO. IOException;Import Java. IO. PrintWriter;Import Java. Util. HashMap;Import Java. Util. Map;Import Javax. servlet. HTTP. HttpServletRequest;Import Javax. servlet. HTTP. HttpServletResponse;import org. Springframework. Web. servlet. Modelandview;Importcom. Alibaba. Druid. Support. JSON. Jsonutils;Importcom. Luo. Exception. Businessexception;import org. Springframework. Web. servlet. Handlerexceptionresolver;public class Mysimplemappingexceptionresolver implements Handlerexceptionresolver {public Modelandview Resolvee Xception (HttpServletRequest request, HttpServletResponse response, Object object, Exception Exception) { Determine if the AJAX request if (!) ( Request. GetHeader("Accept"). IndexOf("Application/json") >-1|| (Request. GetHeader("X-requested-with")! = NULL && request. GetHeader("X-requested-with"). IndexOf("XMLHttpRequest") >-1)) {//If the ajax,jsp format is not returned//For security reasons, only business exceptions we are visible to the front end, otherwise the unification is classified as System exception map<string, object> m AP = new hashmap<string, object> ();Map. Put("Success", false);If (Exception instanceof Businessexception) {map. Put("ErrorMsg", exception. GetMessage());} else {Map. Put("ErrorMsg","System Exception! ");}//Here you need to manually print out the exception, because no log is configured, the actual production environment should be printed to log inside exception. Printstacktrace();For non-Ajax requests, we are all in a unified jump to error. JSPPage return new Modelandview ("/error", map);} else {//If it is an AJAX request, the JSON format returns try {response. setContentType("Application/json;charset=utf-8");PrintWriter writer = Response. Getwriter();map<string, object> map = new hashmap<string, object> ();Map. Put("Success", false);For security reasons, only business exceptions we are visible to the front end, otherwise the unification is classified as System exception if (Exception instanceof Businessexception) {map. Put("ErrorMsg", exception. GetMessage());} else {Map. Put("ErrorMsg","System Exception! ");} writer. Write(jsonutils. toJSONString(map));Writer. Flush();Writer. Close();} catch (IOException e) {E. Printstacktrace();}} return Null;}}
The above code boils down to the following points:
(1) If it is not an AJAX request, then the unity jumps to the error.jsp page, otherwise the JSON data is returned.
(2) If the business is abnormal, we directly print the exception information, otherwise, we are unified system anomalies, if you do not understand the business anomalies here, please read blogger blog: Java exception encapsulation (own definition error code and description, with source).
In addition, you need to add the following configuration in the SPRINGMVC configuration file:
<!-- 框架异常处理Handler --><bean id="exceptionResolver" class="com.luo.exceptionresolver.MySimpleMappingExceptionResolver"></bean>
Here we look directly at the controller code:
PackageCom.luo.controller;ImportJavax.servlet.http.HttpServletRequest;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportOrg.springframework.web.servlet.ModelAndView;ImportCom.luo.errorcode.LuoErrorCode;ImportCom.luo.exception.BusinessException;@Controller Public class usercontroller { @RequestMapping("/index.jhtml") PublicModelandviewGetIndex(HttpServletRequest request)throwsException {Modelandview Mav =NewModelandview ("Index");returnMav }@RequestMapping("/exceptionforpagejumps.jhtml") PublicModelandviewExceptionforpagejumps(HttpServletRequest request)throwsException {Throw NewBusinessexception (Luoerrorcode.null_obj); }@RequestMapping(value="/businessexception.json", Method=requestmethod.post)@ResponseBody PublicStringbusinessexception(HttpServletRequest request) {Throw NewBusinessexception (Luoerrorcode.null_obj); }@RequestMapping(value="/otherexception.json", Method=requestmethod.post)@ResponseBody PublicStringotherexception(HttpServletRequest request)throwsException {Throw NewException (); }}
There's nothing to explain about the controller code, so let's look at the results directly:
(1) If an exception occurs during the jump page, the result of accessing http://localhost:8080/web_exception_project/exceptionForPageJumps.jhtml:
(2) If an exception occurs during the AJAX request, Access http://localhost:8080/web_exception_project/index.jhtml, and then click the Business exception button result:
Click the other exception button results:
(3) Handlerexceptionresolver interface does not handle 404 error, this error we add the following configuration in Web. xml:
<!-- 错误跳转页面 --><error-page> <!-- 路径不正确 --> <error-code>404</error-code> <location>/WEB-INF/view/404.jsp</location></error-page>
Then the 404.jsp code is as follows:
<%@ page language="java" contenttype="text/html; Charset=utf-8 "pageencoding="UTF-8"%><taglib uri="Http://java.sun.com/jsp/jstl/core" prefix="C" / ><html><head><title>Error page</title></head><body>The page was sucked away by a black hole ...</body></html>
Then access a nonexistent connection: http://localhost:8080/web_exception_project/123456.jhtml, the result is as follows:
Third, the source code download
If you re-create the project and then various configurations, download the blogger's project to try it out:
http://download.csdn.net/detail/u013142781/9424969
Javaweb exception Prompt Information unified processing (using SPRINGMVC, with source)