Spring框架异常或非法输入场景下如何实现URL重定向并返回提示信息
解决方案
核心结论
Spring 没有能直接满足你全部需求的单一内置注解,但可以通过现有组件组合实现,无需修改原有控制器的业务代码,代码量极小。
具体实现步骤
1. 开启未知参数异常抛出配置
首先需要让Spring在接收到不支持的请求参数(比如你举的expInp4)时主动抛出异常,而非自动忽略,添加以下配置即可:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseTrailingSlashMatch(true); } @Bean public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); // 遇到未知请求参数直接抛出异常 adapter.setIgnoreUnknownRequestParameters(false); return adapter; } }
如果是Spring Boot项目,也可以在application.properties中补充以下配置处理资源映射冲突:
# 找不到请求处理器时抛出异常,而非返回默认404页面 spring.mvc.throw-exception-if-no-handler-found=true # 关闭默认静态资源映射(如果你的项目没有静态资源需要托管可以开,否则自行调整路径匹配规则) spring.web.resources.add-mappings=false
2. 编写全局异常处理器
通过@ControllerAdvice统一拦截所有参数异常、业务异常,完成重定向逻辑,同时返回你需要的ClientResponse异常信息:
@ControllerAdvice public class GlobalRequestExceptionHandler { // 拦截所有请求参数相关异常:未知参数、参数类型不匹配、缺少必填参数、参数校验不通过 @ExceptionHandler({ ServletRequestBindingException.class, TypeMismatchException.class, ConstraintViolationException.class, MissingServletRequestParameterException.class }) public ResponseEntity<ClientResponse> handleInvalidRequest(Exception e) { // 构造你需要的错误响应对象 ClientResponse errorResp = new ClientResponse(); // 这里可以根据异常类型自定义提示信息 errorResp.setMessage("请求参数非法:" + e.getMessage()); errorResp.setCode(400); // 配置重定向头 HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create("/v1.0/hello/")); // 返回302状态码+重定向地址+错误响应体 return new ResponseEntity<>(errorResp, headers, HttpStatus.FOUND); } // 也可以拦截自定义业务异常,处理业务逻辑校验失败的场景 @ExceptionHandler(BusinessException.class) public ResponseEntity<ClientResponse> handleBusinessError(BusinessException e) { ClientResponse errorResp = new ClientResponse(); errorResp.setMessage("请求处理失败:" + e.getErrorMsg()); errorResp.setCode(e.getErrorCode()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create("/v1.0/hello/")); return new ResponseEntity<>(errorResp, headers, HttpStatus.FOUND); } }
3. 可选:参数规则校验
如果需要对参数取值范围做校验,直接在原有控制器的参数上添加JSR-380校验注解即可,不需要写额外逻辑:
@GetMapping("/v1.0/hello/{userName}") public ClientResponse getDetails(@PathVariable(value = "userName") String userName, @RequestParam(value = "expInp1", required = false) @Min(0) @Max(100) int expInp1, @RequestParam(value = "expInp2", required = false) @Min(1) int expInp2, @RequestParam(value = "expInp3", required = false) int expInp3){ // 原有业务逻辑无需修改 return clientResponse; }
说明
上述实现完全基于Spring自带能力,不需要引入额外依赖,原有控制器代码几乎不需要修改,所有异常和重定向逻辑统一收敛维护,符合你的需求。
内容的提问来源于stack exchange,提问作者Dean Taler
相关产品推荐
相关产品推荐

