java controller 異常捕獲


 

package com.aiyusheng.framework.exception;

import lombok.Data;

/**
 * base異常類
 * @author :cza
 * @date :2020/11/25 15:57
 * @description :
 * @modyified By:
 */
@Data
public class BaseException extends Exception {
    private String code;

    public BaseException(Throwable throwable){
        super(throwable);
    }
    public BaseException(String msg){
        super(msg);
    }
    public BaseException(String msg,Throwable throwable){
        super(msg,throwable);
    }

    @Deprecated
    public BaseException(Throwable throwable,String msg,String code){
        super(msg,throwable);
        this.code=code;
    }
}

 

package com.aiyusheng.framework.exception;

import com.aiyusheng.framework.core.enums.ReturnCode;
import com.aiyusheng.framework.utils.CommUtil;
import lombok.Data;

import javax.swing.plaf.PanelUI;
import java.io.Serializable;

/**
 * 業務異常類
 * @author :cza
 * @date :2020/11/25 15:57
 * @description :
 * @modyified By:
 */

public class BusinessException extends BaseException implements Serializable {

    private static final long serialVersionUID = -3598204678161713009L;

    /**
     * 結果碼
     */
    private String code;

    /**
     * 提示消息
     */
    private String msg;
    /**
     * 提示消息,用於填充properties中的{}參數
     */
    private String [] msgParams;


    /**
    * 功能描述:不帶信息參數的異常<br>
    * @Param code
   * @Param throwable
    * @Return
    * @Author: cza
    * @Date:  2020-11-26
     * */
    public  BusinessException(String code,Throwable throwable){
        super(CommUtil.getResultMsg(code,null),throwable);
        this.code=code;
        this.setCode(code);
    }

    /**
     * 功能描述:不帶信息參數的異常<br>
     * @Param code
     * @Param throwable
     * @Return
     * @Author: cza
     * @Date:  2020-11-26
     * */
    public  BusinessException(ReturnCode returnCode){
        super(returnCode.getMsg());
        this.setCode(returnCode.getCode());
    }


    public BusinessException(ReturnCode returnCode,String [] msgParams,Throwable throwable){
        super(CommUtil.getResultMsg(returnCode.getMsg(),msgParams),throwable);
        this.code=returnCode.getCode();
        //不直接傳遞引用是處於代碼安全考慮,避免位置調用者修改引用內容
        this.msgParams=msgParams.clone();
        this.setCode(returnCode.getCode());
    }

    /**
    * 功能描述:帶一個信息參數的異常
    * @Param:
    * @Return
    * @Author: chenzhian
    * @Date:2020-11-26
    */
    public BusinessException(String code,String  msgParam,Throwable throwable){
        super(CommUtil.getResultMsg(code, new String [] {msgParam}),throwable);
        this.code=code;
        //不直接傳遞引用是處於代碼安全考慮,避免位置調用者修改引用內容
        this.msgParams[0]=msgParam;
        this.setCode(code);
    }

    /**
     * 功能描述: 帶多個信息參數的異常
     * @Param:
     * @param code
     * @param msgParams
     * @param throwable
     * @Return:
     * @Author: chenzhian
     * @Date: 2020/11/26 15:43
     * @Description:
     */
    @Deprecated
    public BusinessException(String code,String [] msgParams,Throwable throwable) {
        super(CommUtil.getResultMsg(code,msgParams),throwable);
        this.code=code;
        //不直接傳遞引用是處於代碼安全考慮,避免位置調用者修改引用內容
        this.msgParams=msgParams.clone();
        this.setCode(code);
    }

    /**
     * 功能描述: 帶多個信息參數的異常
     * @Param:
     * @param code
     * @param throwable
     * @param msgParams
     * @Return:
     * @Author: chenzhian
     * @Date: 2020/11/26 15:45
     * @Description:
     */
    public BusinessException(String code,Throwable throwable,String... msgParams) {
        super(CommUtil.getResultMsg(code,msgParams),throwable);
        this.code=code;
        //不直接傳遞引用是處於代碼安全考慮,避免位置調用者修改引用內容
        this.msgParams=msgParams.clone();
        this.setCode(code);
    }

    /**
     * 功能描述: 異常信息構造函數,用於FA框架反射調用
     * @Param:
     * @param resultMsg
     * @Return:
     * @Author: chenzhian
     * @Date: 2020/11/26 15:46
     * @Description:
     */
    public BusinessException(String resultMsg){
        super(resultMsg);
    }

    @Override
    public String getCode(){
        return code;
    }

    @Override
    public void setCode(String code){
       this.code=code;
    }


    public String [] getMsgParams() {
        //不直接返回msgParams引用為了代碼安全,避免被未知調用者修改引用的內容
        return msgParams.clone();
    }

    public void setMsgParams(String [] msgParams){
        //不直接復制msgParams引用為了代碼安全,避免被未知調用者修改引用的內容
        this.msgParams=msgParams.clone();
    }


    /**
     * 功能描述:
     * @Param: [returnCode, msgParam, throwable]
     * @Return:
     * @Author:
     * @Date: 2020/11/26 14:37
     * @Description:
    public BusinessException(ReturnCode returnCode,String  msgParam,Throwable throwable){
        super(CommUtil.getResultMsg(returnCode.getMsg(), new String [] {msgParam}),throwable);
        this.code=returnCode.getCode();
        //不直接傳遞引用是處於代碼安全考慮,避免位置調用者修改引用內容
        this.msgParams[0]=msgParam;
        this.setCode(returnCode.getCode());
    }*/
}
package com.aiyusheng.framework.core;

import com.aiyusheng.framework.core.enums.ReturnCode;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.shiro.crypto.hash.Hash;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :cza
 * @date :2020/11/26 20:41
 * @description :
 * @modyified By:
 */
@Data
@Accessors(chain = true)
public class ResponseResult<T> implements Serializable {
    private String code;
    private  String msg;
    private T data;

    public ResponseResult(){
        this(ReturnCode.Common.SUCCESS,null);
    }
    public ResponseResult(T data){
        this(ReturnCode.Common.SUCCESS,data);
    }
    public ResponseResult(ReturnCode returnCode){
        this(returnCode,null);
    }
    public ResponseResult(ReturnCode returnCode,T data){
        //this(returnCode,null);
        this.code=returnCode.getCode();
        this.msg=returnCode.getMsg();
    }
    public ResponseResult(String  code,String msg){
        this.code=code;
        this.msg=msg;
        this.data=transferNull2EmptyFloag?(T)"":null;
    }

    public ResponseResult(String  code,String msg,T data){
        this.code=code;
        this.msg=msg;
        this.data=transNullToEmptyString(data);
    }

    public static <T> ResponseResult<T> success(T data){
        return new ResponseResult<>(data);
    }
    public  static  <T> ResponseResult<T> success(T data,String message){
        return new ResponseResult<>(data).setMsg(message);
    }
    public static <T> ResponseResult<T> success(){
        return new ResponseResult<>();
    }
    public static <T> ResponseResult<T> error(String errorMsg){
        return new ResponseResult<>(ReturnCode.Common.RUNTIME_EXCEPTION.getCode(),errorMsg);
    }
    public static <T> ResponseResult<T> error(String errorCode,String errorMsg){
        return new ResponseResult<>(errorCode,errorMsg);
    }
    
    /**
  * 功能描述:檢查是否成功
  * @Param:
  * @Return: boolean
  * @Author: chenzhian
  * @Date: 2020/11/27 11:13
  * @Description:
  */
    public boolean checkResult(){
        return ReturnCode.Common.SUCCESS.getCode().equals(code);
    }
    /**
     * 功能描述:復制code和msg信息
     * @Param:
     * @Return: com.aiyusheng.framework.core.ResponseResult<M>
     * @Author: chenzhian
     * @Date: 2020/11/27 11:18
     * @Description:
     */
    public  <M> ResponseResult<M> copy(){
        return new ResponseResult<>(this.code,this.msg);
    }
    /**
     * 功能描述: 復制code和msg信息,並設置data數據
     * @Param:
     * @Return: com.aiyusheng.framework.core.ResponseResult<M>
     * @Author: chenzhian
     * @Date: 2020/11/27 11:18
     * @Description:
     */
    public  <M> ResponseResult<M> copyAndSetData(){
        return new ResponseResult<>(this.code,this.msg);
    }

    @Override
    public String toString() {
        Map<String,Object> jsonMap=new HashMap<>();
        jsonMap.put("code",this.code);
        jsonMap.put("msg",this.msg);
        jsonMap.put("data",transNullToEmptyString(this.data));
        return JSONPObject.toJSONString(jsonMap, SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteDateUseDateFormat);
    }

    @Deprecated
    private T transNullToEmptyString(T data) {
        if(null==data){
            return transferNull2EmptyFloag?(T)"":data;
        }
        return data;
    }

    public static volatile boolean transferNull2EmptyFloag=false;
}
package com.aiyusheng.framework.core.enums;

/**
 * @author :cza
 * @date :2020/11/26 11:15
 * @description :
 * @modyified By:
 */
public interface ReturnCode {
    public String getCode();
    public  String getMsg();
    public  String getMsg(String code);
    /**
     * 功能描述:定義框架級別的編碼 <br>
     * @Param:
     * @Return
     * @Author:
     * @Date:
     */
    public  enum  Common implements ReturnCode{
        /**
         成功
         */
        SUCCESS("00000","成功"),
        /**
         服務器繁忙 fixme
         */
        BUSINESS_PROCESS_FAILED("950001","服務器繁忙"),
        /*
        字段校驗非法
        */
        INVAID_PARAM("940001","字段校驗非法"),
        /*
         運行時異常
        */
        INVAID_REQUEST_MSG("940001","運行時異常"),
        /*
         token 校驗不通過
         1.1.8 版本之前是非法用戶
        */
        INVAID_VIRTUAL_USER("940102","非法虛擬用戶"),
        /*
       請求參數錯誤()
       */
        INVAID_REQUEST("940103","請求方式錯誤"),

        /*
  運行時異常()
  */
        RUNTIME_EXCEPTION("950102","運行時異常"),



        GATE_EXCEPTION("940502","網關繁忙"),
        CLIENT_ABORT("950504","請求超時");


        private String code;
        private  String msg;
        private Common(String code,String msg){
            this.code=code;
            this.msg=msg;
        }

        public String getCode() {
            return code;
        }

        public String getMsg() {
            return msg;
        }

        public String getMsg(String code) {
            return msg;
        }
    }
}

 

 

/**
 * @author :cza
 * @date :2020/11/25 15:56
 * @description :
 * @modyified By:
 */

import com.aiyusheng.framework.core.ResponseResult;
import com.aiyusheng.framework.core.enums.ReturnCode;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); public static final String FINAL_MESSAGE="服務器內部錯誤,請聯系系統管理員"; /** * 功能描述:自定義后的異常處理 * @Param: * @param ex * @Return: com.aiyusheng.framework.core.ResponseResult * @Author: chenzhian * @Date: 2020/12/3 19:21 * @Description: */ @ExceptionHandler(value = BusinessException.class) public ResponseResult BusinessExceptionHandle(BusinessException ex) { ex.printStackTrace(); //記錄日志 logger.error("\nBusinessExceptionHandle {}", getStackTrace(ex)); String code=ex.getCode(); String message=FINAL_MESSAGE; if(ex.getMsgParams()!=null&&ex.getMsgParams().length>0){ message= Arrays.toString(ex.getMsgParams()); } return new ResponseResult(ReturnCode.Common.BUSINESS_PROCESS_FAILED, "服務器內部錯誤,請聯系系統管理員!"); } /** 獲取堆棧信息 * 功能描述: * @Param: * @param throwable * @Return: java.lang.Throwable * @Author: chenzhian * @Date: 2020/12/3 19:25 * @Description: */ private String getStackTrace(Throwable throwable) { StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); try { throwable.printStackTrace(pw); return sw.toString(); } finally { pw.close(); } } /** * 功能描述: 統一攔截自定義異常 * @Param: * @param ex * @Return: com.aiyusheng.framework.core.ResponseResult * @Author: chenzhian * @Date: 2020/12/3 19:21 * @Description: */ @ExceptionHandler(value = Exception.class) public ResponseResult exceptionHandle(Exception ex) { //根據某個類型進行具體返回 /* if(e instanceof BadRequestException){ return new ResponseResult(400, e.getMessage()); } if(e instanceof NoAuthorityException){ return new BaseResponse(401, e.getMessage()); } if(e instanceof FailureException){ return new BaseResponse(500, e.getMessage()); } else {//其他未捕獲異常 LOGGER.error("exception:{}", e.getMessage(), e);}*/ return new ResponseResult(ReturnCode.Common.BUSINESS_PROCESS_FAILED, "服務器內部錯誤,請聯系系統管理員!"); } /** * 攔截@RequestBody上validate失敗后拋出的異常:MethodArgumentNotValidException */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseResult parameterExceptionHandler(MethodArgumentNotValidException e) { logger.error("exception:{}", e.getMessage()); return new ResponseResult(ReturnCode.Common.BUSINESS_PROCESS_FAILED, "服務器內部錯誤,請聯系系統管理員!"); } }

 

 

引用包

  <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>9.0.33</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
    </dependencies>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM