c global 拦截 ajax,@RestControllerAdvice 全局拦截异常(示例代码)

本文介绍了一个Spring Boot应用中的全局异常处理器,处理了不同类型的异常,包括权限验证、请求方式不支持、运行时异常、系统异常和业务异常,并根据请求类型返回JSON或重定向视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*** 全局异常处理器

*

*@author*/@RestControllerAdvicepublic classGlobalExceptionHandler

{private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);/*** 权限校验失败 如果请求为ajax返回json,普通请求跳转页面*/@ExceptionHandler(AuthorizationException.class)publicObject handleAuthorizationException(HttpServletRequest request, AuthorizationException e)

{

log.error(e.getMessage(), e);if(ServletUtils.isAjaxRequest(request))

{returnAjaxResult.error(PermissionUtils.getMsg(e.getMessage()));

}else{

ModelAndView modelAndView= newModelAndView();

modelAndView.setViewName("error/unauth");returnmodelAndView;

}

}/*** 请求方式不支持*/@ExceptionHandler({ HttpRequestMethodNotSupportedException.class})publicAjaxResult handleException(HttpRequestMethodNotSupportedException e)

{

log.error(e.getMessage(), e);return AjaxResult.error("不支持‘ " + e.getMethod() + "‘请求");

}/*** 拦截未知的运行时异常*/@ExceptionHandler(RuntimeException.class)publicAjaxResult notFount(RuntimeException e)

{

log.error("运行时异常:", e);return AjaxResult.error("运行时异常:" +e.getMessage());

}/*** 系统异常*/@ExceptionHandler(Exception.class)publicAjaxResult handleException(Exception e)

{

log.error(e.getMessage(), e);return AjaxResult.error("服务器错误,请联系管理员");

}/*** 业务异常*/@ExceptionHandler(BusinessException.class)publicObject businessException(HttpServletRequest request, BusinessException e)

{

log.error(e.getMessage(), e);if(ServletUtils.isAjaxRequest(request))

{returnAjaxResult.error(e.getMessage());

}else{

ModelAndView modelAndView= newModelAndView();

modelAndView.addObject("errorMessage", e.getMessage());

modelAndView.setViewName("error/business");returnmodelAndView;

}

}/*** 自定义验证异常*/@ExceptionHandler(BindException.class)publicAjaxResult validatedBindException(BindException e)

{

log.error(e.getMessage(), e);

String message= e.getAllErrors().get(0).getDefaultMessage();returnAjaxResult.error(message);

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值