全局異常捕捉

前言

如題,部分代碼來自百度

代碼

package com.xiben.pm.file.system.init.exception;

import com.xiben.pm.file.system.dto.RestCode;
import lombok.Data;

/**
 * @author :qilong sun
 * @date :Created in 2020/4/7 12:58
 * @description:自定義異常 ps:spring 對於 RuntimeException 異常纔會進行事務回滾。
 * @modified By:
 * @version: V1.0$
 */
@Data
public class MyException extends RuntimeException {
    /**
     * 編碼
     */
    private Integer code = RestCode.FAILURE.getCode();
    /**
     * 描述
     */
    private String msg = RestCode.FAILURE.getMsg();

    public MyException(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public MyException(String msg) {
        this.msg = msg;
    }
}

package com.xiben.pm.file.system.init.exception;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.xiben.pm.file.system.dto.RestCode;
import com.xiben.pm.file.system.dto.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
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.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 全局異常處理器
 * https://blog.csdn.net/jinjiankang/article/details/89711493
 *
 * @author qilong.sun
 */
@ControllerAdvice
@Slf4j
public class GlobalDefaultExceptionHandler {
    /**
     * 用來處理bean validation異常
     * @param ex
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public RestResponse resolveConstraintViolationException(ConstraintViolationException ex){
        RestResponse failure = RestResponse.failure();
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        if(!CollectionUtils.isEmpty(constraintViolations)){
            StringBuilder msgBuilder = new StringBuilder();
            for(ConstraintViolation constraintViolation :constraintViolations){
                msgBuilder.append(constraintViolation.getMessage()).append(",");
            }
            String errorMessage = msgBuilder.toString();
            if(errorMessage.length()>1){
                errorMessage = errorMessage.substring(0,errorMessage.length()-1);
            }
            failure.setMsg(errorMessage);
            return failure;
        }
        failure.setMsg(ex.getMessage());
        return failure;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public RestResponse resolveMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        RestResponse failure = RestResponse.failure();
        List<ObjectError>  objectErrors = ex.getBindingResult().getAllErrors();
        if(!CollectionUtils.isEmpty(objectErrors)) {
            StringBuilder msgBuilder = new StringBuilder();
            for (ObjectError objectError : objectErrors) {
                msgBuilder.append(objectError.getDefaultMessage()).append(",");
            }
            String errorMessage = msgBuilder.toString();
            if (errorMessage.length() > 1) {
                errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
            }
            failure.setMsg(errorMessage);
            return failure;
        }
        failure.setMsg(ex.getMessage());
        return failure;
    }

    /**
     * 攔截捕捉自定義異常 MyException.class
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Map myErrorHandler(MyException ex) {
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;
    }

    /**
     * 處理 Exception 類型的異常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResponse defaultExceptionHandler(Exception e) {
        log.error(e.getMessage());
        String errmsg;
        if (e instanceof NoHandlerFoundException) {
            return RestResponse.failure(RestCode.NOT_FOUND);
        } else if(e instanceof InvalidFormatException) {
            return RestResponse.failure(RestCode.ERROR);
        } else {
            errmsg = RestCode.ERROR.getMsg();
        }
        RestResponse restResponse = new RestResponse();
        restResponse.setMsg(errmsg);
        restResponse.setCode(RestCode.FAILURE.getCode());
        return restResponse;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章