spring @ControllerAdvice统一异常处理 Ajax和普通请求


import com.alibaba.fastjson.JSON;
import com.zh.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 统一异常处理
 * Created by PengHongfu 2018/12/13 15:16
 */
@Slf4j
@ControllerAdvice
public class MyExceptionHandler {
    public static final String ERROR_VIEW = "404";

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest reqest,
                               HttpServletResponse response, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        if (isAjax(reqest)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            //具体操作
            writer.write(JSON.toJSONString(Result.errorOf(HttpStatus.NOT_FOUND.value(), e.getMessage())));
            //
            writer.flush();
            writer.close();
            return null;
            //return Result.errorOf(HttpStatus.NOT_FOUND.value(), e.getMessage());
        } else {
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e.getMessage());
            mav.addObject("url", reqest.getRequestURL());
            mav.setViewName(ERROR_VIEW);
            return mav;
        }
    }

    /**
     * 判断是否是ajax请求
     */
    public static boolean isAjax(HttpServletRequest httpRequest) {
        return (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals(httpRequest.getHeader("X-Requested-With").toString()));
    }
}


import lombok.Data;

public class Result<T> {
    /**
     * 不支持的参数值
     */
    public static final int ERROR_CODE_UN_SUPPORT_ARGUMENTS_VALUE = -3;
    public static final int ERROR_CODE_UN_SUPPORT_ACTION = -4;
    public static Result SYSTEM_ERR = errorOf(-1, "系统错误");
    int resCode;
    String resMessage;
    T data;

    public static <O> Result<O> sucessOf(O object) {
        Result<O> result = new Result<O>();
        result.resCode = 0;
        result.resMessage = "成功";
        result.data = object;
        return result;
    }

    public static Result errorOf(int errorCode, String message) {
        Result result = new Result();
        result.resCode = errorCode;
        result.resMessage = message;
        return result;
    }
}

你可能感兴趣的:(Java)