如何在Java RESTful API中实现URI不匹配时的异常处理器,返回指定JSON格式的404响应?
嘿,我来帮你搞定这个URI不匹配的异常处理问题!针对你需要的场景,我分两种常用技术栈给你具体实现方案:
Spring Boot 实现方案
这是Java生态里开发RESTful API最常用的框架,实现步骤很清晰:
开启NoHandlerFoundException抛出
首先在你的application.properties(或者application.yml)里添加配置,让Spring在找不到对应URI的处理器时抛出异常:spring.mvc.throw-exception-if-no-handler-found=true spring.web.resources.add-mappings=false👉 解释:第一个配置让Spring不再返回默认的404页面,而是抛出异常;第二个配置关闭静态资源映射,避免静态资源请求被误拦截。
编写全局异常处理器
创建一个全局异常处理类,专门捕获NoHandlerFoundException并返回你需要的JSON格式:import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { // 处理URI不匹配的异常 @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity<Map<String, Object>> handleUriNotFound(NoHandlerFoundException ex) { Map<String, Object> response = new HashMap<>(); response.put("response_code", "404"); response.put("message", "uri not found"); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } // 你的正常业务接口示例(比如generateNumber) // @GetMapping("/test/generateNumber") // public ResponseEntity<Map<String, Object>> generateNumber() { // Map<String, Object> response = new HashMap<>(); // response.put("response_code", "200"); // return new ResponseEntity<>(response, HttpStatus.OK); // } }👉 解释:
@RestControllerAdvice会让这个类作用于所有的REST控制器,@ExceptionHandler指定要处理的异常类型,最后构造符合要求的响应体返回。
Node.js Express 实现方案
如果是用Node.js开发REST API,Express框架的实现更简单:
只需要把一个“兜底”路由放在所有业务路由的最后,它会捕获所有未被匹配的请求:
const express = require('express'); const app = express(); // 正常业务接口:匹配正确的URI app.get('/test/generateNumber', (req, res) => { res.json({ response_code: "200" }); }); // 兜底路由:捕获所有未匹配的URI app.all('*', (req, res) => { res.status(404).json({ response_code: "404", message: "uri not found" }); }); // 启动服务 app.listen(8080, () => { console.log('Server running on http://localhost:8080'); });
👉 解释:app.all('*')会匹配所有HTTP方法(GET/POST/PUT等)和所有未被前面路由匹配的URI,然后返回你需要的404格式响应。
内容的提问来源于stack exchange,提问作者Tora
相关产品推荐
相关产品推荐

