全局异常处理

472 阅读1分钟

一、定义全局异常处理器

使用@ControllerAdvice注解和@ExceptionHandler注解

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ModelAttribute
    public void addAttributes(Model model){
        model.addAttribute("message","所有RequestMapping方法都可以获取此信息");
    }
    
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.setDisallowedFields("ids");
    }
    
    /**
     * 拦截处理OperateNotSupportException类的异常
     */
    @ExceptionHandler(OperateNotSupportException.class)
    public ResultData<String> operateNotSupportException(OperateNotSupportException e) {
        log.warn(e.getMessage());
        return ResultData.error(e.getMessage());
    }
    
    /**
     * 拦截处理BusinessException类的异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResultData<String> businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return ResultData.error(e.getMessage());
    }
    
    /**
     * 拦截处理RuntimeException类的异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResultData<String> notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return ResultData.error(e.getMessage());
    }
}

二、自定义异常

/**
 * 业务异常
 * @author pengtech
 */
public class BusinessException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	protected final String message;
	
	public BusinessException(String message) {
		this.message = message;
	}
	
	@Override
	public String getMessage() {
		return "业务异常:" + message;
	}
}

三、方法中抛出异常

@Override
public boolean updateDictData(DictData dict) throws BusinessException {
    if (checkRepeated(dict.getDictType(), dict.getDictValue())){
        throw new BusinessException("字典类型和字典值已存在,不能重复添加!");
    }
    return updateById(dict);
}