SpringBoot异常处理

@RestControllerAdvice(annotations = { RestController.class, Controller.class })
public class BaseExceptionHandler {
	private final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 请求参数类型错误异常的捕获
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = { BindException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	public CommonResult<String> badRequest(BindException e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		return new CommonResult<>(ResponseErrorEnums.BAD_REQUEST);
	}

	/**
	 * 404错误异常的捕获
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = { NoHandlerFoundException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.NOT_FOUND)
	public CommonResult<String> badRequestNotFound(BindException e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		return new CommonResult<>(ResponseErrorEnums.NOT_FOUND);
	}

	/**
	 * mybatis未绑定异常
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BindingException.class)
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public CommonResult<String> mybatis(Exception e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		return new CommonResult<>(ResponseErrorEnums.BOUND_STATEMENT_NOT_FOUNT);
	}

	/**
	 * 自定义异常的捕获 自定义抛出异常。统一的在这里捕获返回JSON格式的友好提示。
	 * 
	 * @param exception
	 * @param request
	 * @return
	 */
	@ExceptionHandler(value = { BaseException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public <T extends Serializable> CommonResult<T> sendError(BaseException exception, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("occurs error when execute url ={} ,message {}", requestURI, ExceptionUtils.getFullStackTrace(exception));
		return new CommonResult<>(exception.getCode(),
				StringUtil.isNotEmpty(exception.getMessage()) ? exception.getMessage() : exception.getDetailMessage());
	}

	/**
	 * 数据库操作出现异常
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = { SQLException.class, DataAccessException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public CommonResult<String> systemError(Exception e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		if(e instanceof MyBatisSystemException){
		    return new CommonResult<>(((MyBatisSystemException) e).getRootCause().getMessage());
        }else{
        	CommonResult<String> commonResult = new CommonResult<>(ResponseErrorEnums.DATABASE_ERROR);
        	commonResult.setMessage(String.format("%s:%s", commonResult.getMessage(), ExceptionUtils.getRootCauseMessage(e)));
            return commonResult;
		}
    }

	/**
	 * 网络连接失败!
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = { ConnectException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public CommonResult<String> connect(Exception e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		return new CommonResult<>(ResponseErrorEnums.CONNECTION_ERROR);
	}

	@ExceptionHandler(value = { RuntimeException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public CommonResult<String> runTimeError(Exception e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		String errorMsg = ExceptionUtils.getRootCauseMessage(e);
		String flowErrorMsg = ThreadMsgUtil.getMapMsg(ThreadMsgUtil.MSG_FLOW_ERROR, true);
		if (StringUtil.isNotEmpty(errorMsg) && errorMsg.indexOf("流程异常") > -1 && StringUtil.isNotEmpty(flowErrorMsg)) {
			errorMsg = flowErrorMsg;
		}else if (StringUtil.isNotEmpty(errorMsg)) {
			errorMsg = errorMsg.replace("RuntimeException:", "");
		}
		return new CommonResult<>(false, errorMsg);
	}

	@ExceptionHandler(value = { Exception.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public CommonResult<String> notAllowed(Exception e) {
		log.error("occurs error when execute method ,message {}", ExceptionUtils.getFullStackTrace(e));
		return new CommonResult<>(ResponseErrorEnums.SYSTEM_ERROR);
	}
	
	/**
	 * 校验错误信息收集
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = { MethodArgumentNotValidException.class })
	@ResponseBody
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public CommonResult<String> MethodArgumentNotValidExceptiona(MethodArgumentNotValidException e) {
		StringBuffer stringBuffer = new StringBuffer();
		BindingResult bindingResult = e.getBindingResult();
		bindingResult.getAllErrors().forEach(error-> stringBuffer.append(error.getDefaultMessage()+" "));
		log.error("occurs error when execute method ,message {}", stringBuffer.toString());
		return new CommonResult<String>(ResponseErrorEnums.ILLEGAL_ARGUMENT.getCode(),stringBuffer.toString());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot提供了一套默认的异常处理机制。一旦程序出现异常,SpringBoot会向/error的URL发送请求,并通过BasicErrorController来处理该请求。默认情况下,SpringBoot会跳转到默认显示异常信息的页面来展示异常信息。如果我们希望将所有的异常统一跳转到自定义的错误页面,可以在src/main/resources/templates目录下创建一个名为error.html的页面。通过覆盖默认的错误页面,我们可以实现自定义的异常处理。 除了使用SpringBoot的默认配置外,还可以通过自定义错误页面来处理异常。我们可以在src/main/resources/templates目录下创建error.html页面,并将其命名为error。通过这种方式,我们可以自定义错误页面的内容和样式来展示异常信息。 在处理异常的过程中,可以关注ErrorMvcAutoConfiguration中的三个关键点。通过对SpringBoot错误处理机制源码的跟踪,我们可以更深入地了解异常处理的实现细节。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot异常处理](https://blog.csdn.net/Linging_24/article/details/126077782)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot 异常处理详解](https://blog.csdn.net/qq_42402854/article/details/91415966)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值