package com.tongsheng.common.advice;
import com.tongsheng.common.constant.Result;
import com.tongsheng.common.constant.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author Yw
* @version 1.0
* @date 2019-12-25
* @description 全局异常处理
*/
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
/**
* shiro权限异常处理
*
* @return result
*/
@ExceptionHandler(AuthorizationException.class)
public Result handleAuthorizationException() {
return Result.getResult(ResultInfo.FORBIDDEN_ERROR);
}
/**
* 处理参数异常
*
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = IllegalArgumentException.class)
@ResponseBody
public Result exceptionHandlerParamsException(IllegalArgumentException e) {
// log.error("处理参数异常", e);
return Result.getResult(ResultInfo.PARAME_EMPTY, e.getMessage());
}
/**
* token无效异常
*/
@ResponseBody
@ExceptionHandler(IncorrectCredentialsException.class)
public Result handleTokenException(IncorrectCredentialsException incorrectCredentialsException) {
log.error("token无效异常", incorrectCredentialsException);
return Result.getResult(ResultInfo.TOKEN_ERROR);
}
/**
* 参数校验异常处理
*
* @return result
*/
@ResponseBody
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result handleMissingParameterException(MissingServletRequestParameterException missingServletRequestParameterException) {
log.error("参数校验异常", missingServletRequestParameterException);
return Result.getResult(ResultInfo.MISSING_PARAMS);
}
/**
* 数字格式化异常处理
*
* @return result
*/
@ResponseBody
@ExceptionHandler(NumberFormatException.class)
public Result handleNumberFormatException(NumberFormatException numberFormatException) {
log.error("数字格式化异常", numberFormatException);
return Result.getResult(ResultInfo.NUMBER_FORMAT_EXCEPTION);
}
/**
* 请求方法错误异常
*
* @param e 请求方法错误异常
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
return Result.getResult(ResultInfo.FAILED, "请求方法出错,你请求的方法" + e.getMethod() + ",该接口支持的方法" + e.getSupportedHttpMethods());
}
/**
* 处理其他异常
*
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result exceptionHandler(Exception e) {
log.error("未知异常!原因是:", e);
return Result.getResult(ResultInfo.SERVER_INTERNAL_EXCEPTION);
}
}
springboot全局异常配置
最新推荐文章于 2025-12-05 17:02:52 发布
本文档介绍了如何使用Spring Boot和Shiro实现全局异常处理,包括权限异常、参数缺失、token验证失败和格式化异常的处理,以及通用异常的统一响应。
2801

被折叠的 条评论
为什么被折叠?



