❤️ 过滤器
过滤器 主要用于对请求和响应进行预处理和后处理
init()在过滤器实例化之后,请求处理之前调用doFilter()该过滤器的核心方法,用于对请求和响应做出处理destroy()在过滤器销毁之前调用
java
@WebFilter("/*") // 注解方式,表示拦截所有路径
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化操作,可以读取filter配置
System.out.println("Filter initialized");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 前置处理:记录请求开始时间
long startTime = System.currentTimeMillis();
System.out.println("Request received at: " + startTime);
// 继续执行下一个过滤器或目标资源
chain.doFilter(request, response);
// 后置处理:计算请求处理时间
long endTime = System.currentTimeMillis();
System.out.println("Request processed in: " + (endTime - startTime) + " ms");
}
@Override
public void destroy() {
// 销毁操作
System.out.println("Filter destroyed");
}
}❤️ 全局异常处理
通过定义全局异常处理器来统一处理抛出的异常 :
@RestControllerAdvice表示这是一个全局异常处理器@ExceptionHandler指定要捕获哪一类型的异常
java
@RestControllerAdvice
public class GlobalExceptionHandle {
/**
* 全局异常处理,捕获所有异常
*/
@ExceptionHandler(Exception.class)
public Result ex(Exception ex) {
return Result.buildResult(Result.Status.UNAUTHORIZED, "禁止访问", "http://localhost:7000/Exception#/Exception");
}
}💛 ProblemDetail
如何使用 :ExceptionHandler 通常会和 ProblemDetail 进行搭配使用
- 扩展字段
setProperty(String key, Object value)
java
@ExceptionHandler(MyBusinessException.class)
public ProblemDetail handleBusinessException(MyBusinessException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
problem.setTitle("Business Rule Violation");
problem.setDetail(ex.getMessage());
problem.setProperty("errorCode", ex.getCode());
return problem;
}
@ExceptionHandler(RuntimeException.class)
public ProblemDetail runtimeExceptionHandler(RuntimeException e) {
log.error(e.getMessage(), e);
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage());
}返回格式 :
type错误类型的标识 URI,错误文档大全(默认为空)title错误的简要描述(不传则为错误码)statushttp 状态码(可以不传)detail具体的错误信息(默认为空)instance出错的具体请求路径或实例 URI(可以不传)
json
{
"type": "https://example.com/errors/not-found",
"title": "Resource Not Found",
"status": 404,
"detail": "The item you requested was not found",
"instance": "/api/items/123"
}