Two Methods for unified Exception Handling using Spring

Source: Internet
Author: User

Two Methods for unified Exception Handling using Spring
1. Custom unified Exception processor custom Exception implementation HandlerExceptionResolver interface or inherit the AbstractHandlerExceptionResolver class
1. Implement 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: Unified Exception Handling. Note that the exception thrown by the Controller layer can be handled here, but do not handle exceptions captured by the Controller (Exceptions captured by the Controller are not processed here) * @ author Jay He * @ date 10:22:11 a.m. on April 9 */public class ExceptionHandler implements HandlerExceptionResolver {private static final Logger LOGGER = Logger. getLogger (ExceptionHandler. class); @ Override public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {LOGGER. error (new Date (). toLocaleString () + "exception information", ex); if (ex instanceof NumberFormatException) {return new ModelAndView ("exception/number");} else if (ex instanceof NullPointerException) {return new ModelAndView ("exception/null");} else if (ex instanceof BusinessException) {return new ModelAndView ("exception/business ");} else if (ex instanceof SocketTimeoutException | ex instanceof 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. inherit 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: Unified Exception Handling. Note that the exception thrown by the Controller layer can be handled here, but do not handle exceptions captured by the Controller (Exceptions captured by the Controller are not processed here) * @ author Jay He * @ date 10:22:11 on April 9, November 4, 2014 **/public class ExceptionHandler extends acthandlerexceptionresolver {private static final Logger LOGGER = Logger. getLogger (ExceptionHandler. class); @ Override protected ModelAndView doResolveException (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ){
LOGGER. error (new Date (). toLocaleString () + "exception information", ex); if (ex instanceof NumberFormatException) {return new ModelAndView ("exception/number");} else if (ex instanceof NullPointerException) {return new ModelAndView ("exception/null");} else if (ex instanceof BusinessException) {return new ModelAndView ("exception/business ");} else if (ex instanceof SocketTimeoutException | ex instanceof 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 ");
}}
 

Add a custom exception handling module to the configuration file
 
     
   
 



Error page display:
Error. jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Error Page
Error Message

Error description
$ {ErrorTips}



Error exception information Stack

$ {Ex}

Eception. jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Exception page
Module Development in progress. Please wait ......




2. implement unified Exception Handling Based on the @ ControllerAdvice annotation to easily return Common exceptions and Ajax exception information and customize 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. servle TRequestUtils; 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. da TeUtil;/*** @ ClassName: WebExceptionHandler * @ Description: exception processor on the Web layer. Here, you can write multiple methods to handle different exceptions and process page Jump requests, jump to the error page specified by the exception. * You can also process Ajax requests. Based on the failure, different prompts are displayed on the page. * operateExp: process common requests * operateExpAjax: handle Ajax requests * @ author Jay He * @ date 5:16:37 on April 9, May 27, 2015 **/@ ControllerAdvicepublic class WebExceptionHandler {Logger logger = Logger. getLogger (WebExceptionHandler. class);/** if UnauthorizedException is thrown Intercepted by the exception processor to display no permission information */@ ExceptionHandler ({UnauthorizedException. class}) @ ResponseStatus (HttpStatus. UNAUTHORIZED) public ModelAndView unauthenticatedException (NativeWebRequest request, UnauthorizedException e) {ModelAndView mv = new ModelAndView (); mv. addObject ("exception", e); mv. setViewName ("base/exception/unauthorized"); return mv;}/*** @ Title: operateExp * @ Description: global exception Control, recording logs * any method has an exception Normally, it will be intercepted by this method. Then, output the log. Encapsulate the Map and return the error message to the page: * Note: the error message returned to the page is only used during development. After going online, remove the error page, only log logs can be printed to 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 ("*************** ------ the exception information has been recorded (" + DateUtil. getNow ("yyyy-MM-dd HH: mm: ss") + ")-------* * ********* "); Request. setAttribute ("errorTips", ex. getMessage (); request. setAttribute ("ex", ex); return "exception/error";}/** records Ajax exception logs, and transmits the error Ajax error information (write-back) to the foreground for display, * The error message -- data. responseText: the error message sent in the background is ** eg: * $. ajax ({type: 'get', dataType: "json", url: ctx + '/test/test', accept: "application/json", success: function (data) {console. log (data) ;}, error: fun Ction (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 ("*************** ------ the exception information has been recorded (" + DateUtil. getNow ("yyyy-MM-dd HH: mm: ss") + ")-------***********"); // write Ajax exception information back to the foreground for page prompt respon Se. getWriter (). write ("sorry, Ajax request Error !!! ") ;}@ ExceptionHandler (ConnectException. class) public void operateExpNetException (ConnectException ex, HttpServletResponse 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 the Ajax exception information back to the foreground for the page prompt response. getWriter (). write ("sorry, network connection Error !!! ");}}



Exception Test
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";} @ RequestMapping (value = "/common", method = RequestMethod. GET) public Map
 
  
CommonExcetion () throws RuntimeException {Map
  
   
Map = new HashMap
   
    
(); Int I = 10; if (I = 10) {throw new RuntimeException ("RunTime exception");} return map ;} @ AjaxExceptionHandler (tips = "try", description = "Haha") @ RequestMapping (value = "/ajax/net", method = RequestMethod. GET) @ ResponseBody public Map
    
     
AjaxConnectionExcetion () throws ConnectException {Map
     
      
Map = new HashMap
      
        (); 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
       
         AjaxExcetion () throws AjaxException {Map
        
          Map = new HashMap
         
           (); Int I = 10; if (I = 10) {throw new AjaxException ("test Ajax exception");} return map ;}}
         
        
       
      
     
    
   
  
 


Front-end page
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% @ Include file = ".../common/meta. jsp" %> <script src = "$ {jqueryCtxPath}/jquery-ui-1.11.2.custom/jquery-ui.min.js"> </script> Normal exception handling test Ajax testing of network connection exceptions Ajax testing of Common exceptions<Script type = "text/javascript"> $ (document ). ready (function () {$ ("# test1 "). click (function () {$. ajax ({type: 'get', dataType: "json", url: ctx + '/exception/ajax/net', accept: "application/json", success: function (data) {console. log (data) ;}, error: function (data, errorThrown) {console. log (data); alert ("error" + data. responseText) ;}}) ;}); $ ("# test2 "). click (function () {$. ajax ({type: 'get', dataType: "json", url: ctx + '/exception/ajax/common', accept: "application/json", success: function (data) {console. log (data) ;}, error: function (data, errorThrown) {console. log (data); alert ("error" + data. responseText) ;}}) ;}); </script>
Page Result demonstration


Related Article

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.