spring 全局异常处理类

spring全局异常处理
@ControllerAdvice 注解包含@Component注解,在context:component-scan扫描包的时候,注意扫描方式,需要把异常处理类扫描进去

package com.admin.exceptioncontroller;

import java.io.IOException;
import java.io.PrintWriter;

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.web.bind.annotation.ControllerAdvice;  
import org.springframework.web.bind.annotation.ExceptionHandler;  
import org.springframework.web.bind.annotation.ResponseStatus;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;  
import org.springframework.web.servlet.NoHandlerFoundException;

import com.admin.controller.BaseController;
import com.admin.enumdata.ServerErrorEnum;
import com.admin.utils.CommonResponse;
import com.admin.utils.JsonUtils;  

@ControllerAdvice(annotations = { RestController.class, Controller.class })//
public class ExceptionReaper extends BaseController{

     private static final Logger logger = LoggerFactory.getLogger(ExceptionReaper.class);

    @ExceptionHandler(value = { IOException.class, RuntimeException.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView exception(Exception exception, HttpServletRequest request, HttpServletResponse response) {

        logger.error(ServerErrorEnum.INTERNAL_SERVER_ERROR.getMessage(), exception);
        if(jsAjaxRequest(request)){
            writeResponse(response, bad(ServerErrorEnum.INTERNAL_SERVER_ERROR.getMessage()));
            return null;
        }
        return new ModelAndView(ServerErrorEnum.INTERNAL_SERVER_ERROR.getErrPage());
    }

    @ExceptionHandler(value = { NoHandlerFoundException.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ModelAndView noMapping(Exception exception, HttpServletRequest request, HttpServletResponse response) {
        logger.error(ServerErrorEnum.ACCESS_NOT_FOUND.getMessage(), exception);
        if(jsAjaxRequest(request)){
            writeResponse(response, bad(ServerErrorEnum.ACCESS_NOT_FOUND.getMessage()));
            return null;
        }
        return new ModelAndView(ServerErrorEnum.ACCESS_NOT_FOUND.getErrPage());
    }

    //是否是ajax请求
    private boolean jsAjaxRequest(HttpServletRequest request) {
        boolean isAjaxRequest = false;

        //如果含有"application/json" 或者含有"XMLHttpRequest" 表明是ajax请求
        if (request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").contains("XMLHttpRequest"))) {
            isAjaxRequest = true;
        }
        return isAjaxRequest;
    }

    //response 写入返回信息
    private void writeResponse(HttpServletResponse response, CommonResponse cRes){
        try {
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtils.toJson(cRes));
            writer.flush();//因为写入的时候是有缓存的,缓存够了才会写入,这块是将缓存中的数据强制写入
            writer.close();//调用close默认调用flush,一般servlet或者spring等框架在response返回的时候,会自动调用close方法,所以不需要显示调用flush和close
        } catch (IOException e) {
            logger.error("spring全局异常捕获类:writer response 异常");
        }
    }
}



package com.admin.enumdata;

public enum ServerErrorEnum {

    INTERNAL_SERVER_ERROR("error/internal_server_error", "spring全局异常捕获类:服务器500异常"),

    ACCESS_NOT_FOUND("error/not_found", "spring全局异常捕获类:服务器404异常");

    private ServerErrorEnum(String errPage, String msg) {
        this.errPage = errPage;
        this.message = msg;
    }

    private String errPage;

    private String message;


    public String getErrPage() {
        return errPage;
    }

    public void setErrPage(String errPage) {
        this.errPage = errPage;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

你可能感兴趣的:(spring)