如何在React中正确捕获Spring Rest Controller返回的错误消息
你遇到的问题由前后端两处逻辑问题共同导致:
- 前端异步执行时序错误:
checkStatus方法中的response.json()是异步操作,你未等待JSON解析完成就直接返回了拒绝态Promise,此时error.error还未完成赋值,所以捕获时取值为undefined。 - 后端Spring Boot默认配置限制:Spring Boot 2.3+版本默认不对外返回自定义异常的message内容,需要手动开启配置,否则即使解析到响应体也拿不到你抛出的错误文本。
第一步:修复前端异步逻辑
修改checkStatus函数,等待JSON解析完成后再抛出错误:
import fetch from "unfetch"; // 使用async await等待异步操作完成 const checkStatus = async (response) => { if (response.ok) { return response; } const error = new Error(response.statusText); error.response = response; // 等待响应体JSON解析完成再赋值 const errorBody = await response.json(); error.error = errorBody; return Promise.reject(error); }; export const getAllStudents = () => fetch("http://localhost:1020/api/students").then(checkStatus);
第二步:修复后端配置(二选一即可)
方案A:开启Spring默认错误返回的message配置
在你的application.properties配置文件中添加如下配置:
server.error.include-message=always
如果使用application.yml则添加:
server: error: include-message: always
方案B:自定义全局异常处理器(更推荐,可控性更高)
新增全局异常处理类,自定义返回的错误结构:
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 java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(IllegalStateException.class) public ResponseEntity<Map<String, String>> handleIllegalStateException(IllegalStateException e) { Map<String, String> errorMap = new HashMap<>(); errorMap.put("message", e.getMessage()); return new ResponseEntity<>(errorMap, HttpStatus.INTERNAL_SERVER_ERROR); } }
修改完成后重新启动前后端服务,你在catch中打印console.log(error.error.message)就能拿到预期的Opps can not get all students文本。
内容的提问来源于stack exchange,提问作者Marquez Ludin Albarado Jaimes
相关产品推荐
相关产品推荐

