1. 程式人生 > >spring @ControllerAdvice統一異常處理 Ajax和普通請求

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;
    }
}