java中的全局异常捕获

首先写一个封装实体的类

package com.citicsc.framework.common.constructure.dto;

import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Date;
@Getter
@Setter
@ToString
@NoArgsConstructor
@Accessors(chain = true)
@EqualsAndHashCode
public class BaseResponseDTO implements Serializable {
    /**
     * requestId from request
     */
    private String requestId;
    /**
     * response DateTime
     */
    private Date responseDateTime = new Date();
    /**
     * response Status
     */
    private ResponseStatusEnum responseStatus;
    /**
     * response error code
     */
    private String responseErrorCode;
    /**
     * response error message
     */
    private String responseErrorMsg;
    /**
     * result
     */
    private T results;

    public static BaseResponseDTO buildFailureResp(String errCode, String errMsg, String requestId) {
        BaseResponseDTO resp = new BaseResponseDTO();
        resp.setResponseDateTime(new Date());
        resp.setResponseStatus(ResponseStatusEnum.FAIL);
        resp.setResponseErrorCode(errCode);
        resp.setResponseErrorMsg(errMsg);
        resp.setRequestId(requestId);
        return resp;
    }

}

然后自定义几个异常

自定义个参数异常

package com.citicsc.galaxy.finance.infrastructure.exceptions;


public class ParamsErrorException extends RuntimeException {

	private static final long serialVersionUID = -5975068082716831797L;
	
	public ParamsErrorException(Exception e) {
		super(e);
    }
	
	public ParamsErrorException(String errorMessage) {
		super(errorMessage);
    }
}

在定义一个全局自己抛出的异常,在使用的时候就会自己new就行了,实例:

            if (dbBillData == null){
                throw new BizException("该账单不存在");
            }
package com.citicsc.galaxy.finance.infrastructure.exceptions;

public class BizException extends RuntimeException{


    /**
	 * 
	 */
	private static final long serialVersionUID = 6131414147309131533L;

	public BizException(String message) {
        super(message);
    }
}

最后定义一个异常的捕获类,在类上面要加上@ControllerAdvice注解

package com.citicsc.galaxy.finance.response;

import com.citicsc.galaxy.finance.infrastructure.exceptions.BizException;
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 com.citicsc.framework.common.constructure.dto.BaseResponseDTO;
import com.citicsc.galaxy.finance.infrastructure.exceptions.ParamsErrorException;
import com.citicsc.galaxy.finance.infrastructure.response.FRExpCodeEnum;
import com.citicsc.galaxy.finance.infrastructure.utils.ResponseUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
	
	@ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResponseDTO handleException(Exception e){
		log.error("### GlobalExceptionHandler.handleException", e);
        return ResponseUtils.fail(FRExpCodeEnum.SYS_ERROR.buildFullExpCode(), FRExpCodeEnum.SYS_ERROR.getErrorMessage());
    }
	
	@ExceptionHandler(ParamsErrorException.class)
    @ResponseBody
    public BaseResponseDTO handleParamsErrorException(ParamsErrorException e){
		log.error("### GlobalExceptionHandler.handleParamsErrorException", e);
        return ResponseUtils.fail(FRExpCodeEnum.PARAMS_ERROR.buildFullExpCode(), e.getMessage());
    }
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResponseDTO handleParamsErrorException(MethodArgumentNotValidException e) {
		log.error("### GlobalExceptionHandler.handleParamsErrorException", e);
        return ResponseUtils.fail(FRExpCodeEnum.PARAMS_ERROR.buildFullExpCode(), 
        		e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public BaseResponseDTO handleBizException(BizException e) {
        log.error("### GlobalExceptionHandler.handleBizException", e);
        return ResponseUtils.fail(FRExpCodeEnum.BUSINESS_ERROR.buildFullExpCode(),e.getMessage());
    }
    
    @ExceptionHandler(IllegalStateException.class)
    @ResponseBody
    public BaseResponseDTO handleIllegalStateException(IllegalStateException e) {
        log.error("### GlobalExceptionHandler.IllegalStateException", e);
        return ResponseUtils.fail(FRExpCodeEnum.BUSINESS_ERROR.buildFullExpCode(),e.getMessage());
    } 
}

你可能感兴趣的:(java,开发语言)