全局異常處理

1、定義全局異常處理器

使用@ControllerAdvice註解和@ExceptionHandler註解web

@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());
    }
}
複製代碼

2、自定義異常

/**
 * 業務異常
 * @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;
	}
}
複製代碼

3、方法中拋出異常

@Override
public boolean updateDictData(DictData dict) throws BusinessException {
    if (checkRepeated(dict.getDictType(), dict.getDictValue())){
        throw new BusinessException("字典類型和字典值已存在,不能重複添加!");
    }
    return updateById(dict);
}
複製代碼
相關文章
相關標籤/搜索