首先创建一个自定义异常类
/**
*自定异常类继承了RuntimeException,使用CODE和message两个属性
*/
public class CustomException extends RuntimeException{
private String code;
public CustomException(String code, String message){
super(message);
this.code = code;
}
public String getCode() {
return code;
}
}
创建全局异常捕获类
/** @ControllerAdvice 是Controller增强器,作用是给Controller控制器添加统一的操作或处理
*搭配 @ExceptionHandler 捕获 上面定义的CustomException
一旦捕获到CustomException,通过全局异常捕获类返回错误码以及错误信息
*/
@ControllerAdvice
public class GlobalExceptionHandle {
@ExceptionHandler(CustomException.class)
@ResponseBody
public void exceptionHandler(Exception e, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.sendError(Integer.parseInt(((CustomException) e).getCode()), e.getMessage());
}
}
使用方法
@RestController
@RequestMapping("/Common")
public class CommonController {@GetMapping("/SayHH")
public String sayH() {
throw new CustomException("403","鉴权失效");
}
}
postman测试返回
{
"timestamp": "2023-02-02T08:44:14.890+0000",
"status": 403,
"error": "Forbidden",
"message": "鉴权失效",
"path": "/Common/SayHH"
}
正如上面演示,通常搭配拦截器进行鉴权校验
Token拦截器如下
public class TokenInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String authorization = request.getHeader("TAuth");
/**此处修改权限鉴定的具体业务*/
if (!StringUtils.isEmpty(authorization)) {
return true;
} else {
throw new CustomException("403", "鉴权失效");
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
写完拦截器后我们需要将拦截器配置上
/**addPathPatterns增加所需拦截的路径excludePathPatterns增加例外路径*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/Common/Say");
}
}
这样一个简单的权限拦截器就完成了