自定义异常+全局异常处理

1、自定义异常

public class MyException extends Exception{

	private static final long serialVersionUID = -1;

	@Getter
	@Setter
	private String errorCode;

	/**
	 * 异常处理类
	 * @param errorCode 错误码
	 * @param message	错误信息
	 */
	public MyException(final String errorCode, final String message) {
		super(message);
		this.errorCode = errorCode;
	}
}

2、全局异常处理

@Slf4j
@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @Resource
    private ConfigurationService configurationService;

    @ExceptionHandler(value = Exception.class)
    public Map defaultErrorHandler(HttpServletRequest req, Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        log.info("全局捕获异常{}", sw.getBuffer().toString());
        log.error("ERROR RequestURL: {}, errorMessage: \n{} ", req.getRequestURL(), e.getMessage());
        Map<String, String> map = new HashMap<>(1);
        if (e instanceof MyException) {
            //业务异常
            String errorCode = ((MyException) e).getErrorCode();
            map.put("code", errorCode);
            map.put("message", e.getMessage());
            if (errorCode.equalsIgnoreCase(Constants.MyExceptionCode.FORCE_UPDATE)) {
                String tip = configurationService.getValueByInnerName(Constants.SysParamsName.FORCE_UPDATE_TIP);
                String aurl = configurationService.getValueByInnerName(Constants.SysParamsName.A_FORCE_UPDATE_URL);
                String iurl = configurationService.getValueByInnerName(Constants.SysParamsName.I_FORCE_UPDATE_URL);
                map.put("updateTip", tip);
                map.put("androidUpdateUrl", aurl);
                map.put("iosUpdateUrl", iurl);
            }
        } else {
            map.put("code", "500000");
            map.put("message", "系统内部错误");
        }
        log.error("errorCode:{}, message:{}", map.get("code"), e.getMessage(), e);
        return map;
    }
}

你可能感兴趣的:(工具类+笔记,自定义异常,全局异常处理)