springmvc global exception handler

Add bean

<-! Unified exception handling -> 
    < bean the above mentioned id = "exceptionHandler" class = "com.ak1ak1.common.shiro.ExceptionHandler" />

Java code

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.ak1ak1.utils.AjaxResult;
import com.alibaba.fastjson.JSON;

/**
 * 
 * @author hejie
 * @date 2019年9月18日
 * @Desc unitary exception
  ModelAndView outJson (HttpServletRequest request, HttpServletResponse response, AjaxResult ajax) {* / 
Public  class the ExceptionHandler the implements the HandlerExceptionResolver { 

    protected  Final Logger Logger = LoggerFactory.getLogger (getClass ()); 

    @Override 
    public ModelAndView the resolveException (the HttpServletRequest Request, Response the HttpServletResponse, Object Handler, Exception EX) { 
        logger.error (ex.getMessage () , EX); 
        // If you do not catch the exception, unified system returned error exception 
        return outJson (request, the Response, AjaxResult.error ( "abnormal system, please contact the administrator!" )); 
    } 

    Private
        Music Videos ModelAndView = new new ModelAndView ();
         / *   used to return response     * / 
        response.setStatus (HttpStatus.OK.value ()); // set the status code 
        the response.setContentType (MediaType.APPLICATION_JSON_VALUE); // Set the ContentType 
        response.setCharacterEncoding ( "UTF-. 8"); // to avoid distortion 
        response.setHeader ( "the Cache-Control", "Cache-NO, MUST-revalidate" );
         the try { 
            . response.getWriter () Write (JSON.toJSONString (Ajax)); 
        } the catch (IOException E) { 
            logger.error ( "abnormal communication with the client:" + e.getMessage (), E); 
        } 
        return Music Videos; 
    } 
}

 

Guess you like

Origin www.cnblogs.com/hjieone/p/11549627.html