Two ways to use spring for uniform exception handling

Source: Internet
Author: User
Tags getmessage log log log4j

1. Custom Unified Exception Handler custom exception implement Handlerexceptionresolver interface or inherit Abstracthandlerexceptionresolver class
1. Implement Interface Handlerexceptionresolver
Package Com.jay.platform.exception.handler;import Java.io.ioexception;import Java.net.connectexception;import Java.net.sockettimeoutexception;import Java.util.date;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.log4j.logger;import Org.springframework.web.servlet.handlerexceptionresolver;import Org.springframework.web.servlet.ModelAndView; Import Com.jay.platform.exception.ajaxexception;import com.jay.platform.exception.businessexception;/** * * @ Classname:exceptionhandler * @Description: Uniform exception handling, note that this can handle exceptions thrown by the controller layer, but does not handle exceptions captured by the controller (the exception that the controller catches), No longer processed here) * @author Jay He * @date November 4, 2014 Morning 10:22:11 * */public class Exceptionhandler implements Handlerexceptionresol    ver {private static final Logger Logger = Logger. GetLogger (Exceptionhandler.class); @Override public Modelandview resolveexception (httpservletrequest request, httpservletresponse response, Object hand Ler, Exception ex) {Logger.error (NEW Date (). toLocaleString () + "exception information", ex), if (ex instanceof NumberFormatException) {return new Modelandview ("exception/n Umber ");} else if (ex instanceof NullPointerException) {return new Modelandview ("Exception/null");} else if (ex instanceof Busin Essexception) {return new Modelandview ("exception/business");} else if (ex instanceof sockettimeoutexception| | Ex Inst    Anceof connectexception) {try {response.getwriter (). Write ("network exception");    } catch (IOException e) {e.printstacktrace (); } return new Modelandview ("Exception/net_error");} else if (ex instanceof ajaxexception) {System.out.println ("-=-=");}    return new Modelandview ("Exception/exception"); }}

2. Inheriting the Abstracthandlerexceptionresolver class
Package Com.jay.platform.exception.handler;import Java.io.ioexception;import Java.net.connectexception;import Java.net.sockettimeoutexception;import Java.util.date;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.log4j.logger;import Org.springframework.web.servlet.handlerexceptionresolver;import Org.springframework.web.servlet.ModelAndView; Import Org.springframework.web.servlet.handler.abstracthandlerexceptionresolver;import Com.jay.platform.exception.ajaxexception;import com.jay.platform.exception.businessexception;/** * * @ClassName: Exceptionhandler * @Description: Uniform exception handling, note that this can handle exceptions thrown by the controller layer, but does not handle exceptions captured by the controller (the exception that the controller catches is not handled here) * @    Author Jay He * @date November 4, 2014 Morning 10:22:11 * */public class Exceptionhandler extends abstracthandlerexceptionresolver{    private static final Logger Logger = Logger. GetLogger (Exceptionhandler.class); @Override protected Modelandview doresolveexception (httpservletrequest Request, HttpServletResponse response, Object handler, Exception ex) {<pre name= "code" class= "Java" >logger.error (New Date (). toLocaleString () + "exception information", ex), if (ex instanceof NumberFormatException) {return new Modelandview ("Exceptio N/number ");} else if (ex instanceof NullPointerException) {return new Modelandview ("Exception/null");} else if (ex instanceof Busin Essexception) {return new Modelandview ("exception/business");} else if (ex instanceof sockettimeoutexception| | Ex Inst    Anceof connectexception) {try {response.getwriter (). Write ("network exception");    } catch (IOException e) {e.printstacktrace (); } return new Modelandview ("Exception/net_error");} else if (ex instanceof ajaxexception) {System.out.println ("-=-=");} return new Modelandview ("Exception/exception");
}}

To add a custom exception handling module to a configuration file
<!--Unified exception handling for Spring MVC--    <bean id= "Exceptionresolver" class= " Com.jay.platform.exception.handler.ExceptionHandler "/>  



Error page display:
error.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


eception.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >





2. Unified exception handling based on @controlleradvice annotations for easy return of common exceptions and Ajax exception information custom Web layer exception handling
Webexceptionhandler.java
Package Com.jay.platform.exception.handler;import Java.io.ioexception;import Java.net.connectexception;import Java.net.sockettimeoutexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.log4j.logger;import Org.apache.shiro.authz.unauthorizedexception;import Org.springframework.http.httpstatus;import Org.springframework.web.bind.servletrequestutils;import Org.springframework.web.bind.annotation.controlleradvice;import Org.springframework.web.bind.annotation.exceptionhandler;import Org.springframework.web.bind.annotation.responsestatus;import Org.springframework.web.context.request.nativewebrequest;import Org.springframework.web.servlet.ModelAndView; Import Com.jay.platform.exception.ajaxexception;import com.jay.platform.utils.dateutil;/** * @ClassName:                                                       Webexceptionhandler * @Description: Web Layer Exception handler,--here can be based on different exceptions, write multiple methods to process, can handle the jump page request, jump to the exception specified error page, * You can also handle AJAX requests, depending on the exception that is not passed, on the pagePolygon output Different message * Operateexp: Handling Ordinary Request * Operateexpajax: Processing ajax Request * @author Jay He * @date May 27, 2015 PM 5:16:37 * */@ControllerAdvicepublic class Webexceptionhandler {Logger Logger = Logg    Er.getlogger (Webexceptionhandler.class); /* * If Unauthorizedexception is thrown, it will be intercepted by the exception handler to display no permission information */@ExceptionHandler ({unauthorizedexception.class}) @Re Sponsestatus (httpstatus.unauthorized) public Modelandview unauthenticatedexception (nativewebrequest request, Unauth Orizedexception e) {modelandview mv = new Modelandview (); Mv.addobject ("Exception", e); Mv.setviewname ("base/exception/    Unauthorized "); return MV; }/** * @Title: Operateexp * @Description: Global exception control, logging * Any method that has an exception is bound to be intercepted by this method. Then, output the log.  Encapsulate map and return to the page display error message: * Special NOTE: Return to the page error message is only used in development, after the online, to remove the error page, only print log log can prevent information leakage * @param: @param ex * @param: @param request * @return: String * @throws: */@ExceptionHandLer (runtimeexception.class) public String operateexp (RuntimeException ex, httpservletrequest request) {Logger.error ( Ex.getmessage (), ex); Logger.info ("*************------exception information is logged (" + dateutil.getnow ("Yyyy-mm-dd HH:mm:ss")-------* "); Request.setattribute (" Errortips ", Ex.getmessage ()); Request.setattribute (" Ex ", Ex); return" exception/    Error "; }/* * Log Ajax exception logs and pass the error AJAX error message (write back) to the foreground to show, * The front desk jquery Ajax request error, you can print a false message-Data.responsetext: Here is the background pass error prompt * Eg: * $.ajax ({type: ' Get ', DataType: "JSON", Url:ctx + '/tes            T/test ', Accept: "Application/json", success:function (data) {Console.log (data);                }, Error:function (data, Errorthrown) {console.log (data);            Alert ("error" + Data.responsetext);     }        }); */@ExceptionHandler (ajaxexception.class) public void Operateexpajax (Ajaxexception ex, HttpservleTresponse response) throws IOException {Logger.error (Ex.getmessage (), ex) Logger.info ("*************------exception information is logged (" + Dateutil.getnow ("Yyyy-mm-dd HH:mm:ss") + ")-------***********");//write Ajax exception information back to the foreground for the page hint Response.getwriter (). Write ("Sorry,ajax request Error!!!"    "); } @ExceptionHandler (Connectexception.class) public void Operateexpnetexception (Connectexception ex, Httpserv Letresponse response) throws IOException {Logger.error (Ex.getmessage (), ex); Logger.info ("*************------    The exception information has been recorded ("+ Dateutil.getnow (" Yyyy-mm-dd HH:mm:ss ") +")-------*********** ");//write Ajax exception information back to the foreground for page prompts Response.getwriter (). Write ("Sorry, network connection Error!!!    "); }}



Anomaly Testing
Package Com.jay.platform.controller.test;import Java.net.connectexception;import Java.util.hashmap;import Java.util.map;import Org.springframework.stereotype.component;import Org.springframework.stereotype.Controller; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.responsebody;import Com.jay.platform.annotation.AjaxExceptionHandler; Import com.jay.platform.exception.AjaxException; @Component @controller () @RequestMapping ("Exception") public class    Exceptionhandlertestcontroller {@RequestMapping ("test") public String Getit () {return "exception/test/test"; } @RequestMapping (value= "/common", method=requestmethod.get) public map<string, object> commonexcetion () t Hrows runtimeexception{map<string, object> Map = new hashmap<string, object> (); int i=10;if (i==10) {throw new RuntimeException ("runtime exception");}    return map; } @AjaxExceptionHandLer (tips= "Try", description= "Ha") @RequestMapping (value= "/ajax/net", Method=requestmethod.get) @ResponseBody Publi C map<string, Object> ajaxconnectionexcetion () throws connectexception{map<string, Object> Map = new HashMap <string, object> (); int i=10;if (i==10) {throw new Connectexception ("Test network connection Exception");}    return map; } @RequestMapping (value= "/ajax/common", Method=requestmethod.get) @ResponseBody public map<string, OBJECT&G T Ajaxexcetion () throws ajaxexception{map<string, object> Map = new hashmap<string, object> (); int i=10;if (i== {throw new Ajaxexception ("Test ajax Exception");}    return map; }}


Front Page
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Page Results Demo


Two ways to use spring for uniform exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.