在前后端分离的开发架构中,前端使用JavaScript调用后端Spring框架提供的接口时,难免会出现参数错误、业务逻辑异常、系统运行错误等问题,需要通过合理的异常处理机制,让前端能准确获取异常信息并做出对应的用户提示。

后端Spring异常处理实现
1. 自定义业务异常类
首先可以自定义一个业务异常类,用来区分业务层面的异常和系统层面的异常,方便后续分类处理。
// 自定义业务异常类
public class BusinessException extends RuntimeException {
// 异常状态码
private Integer code;
// 异常提示信息
private String message;
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2. 编写全局异常处理器
使用Spring的@RestControllerAdvice注解编写全局异常处理器,统一捕获所有接口抛出的异常,返回规范化的响应给前端。
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
// 处理自定义业务异常
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) {
Map<String, Object> result = new HashMap<>();
result.put("code", e.getCode());
result.put("message", e.getMessage());
result.put("data", null);
// 业务异常返回200状态码,用code区分异常类型
return new ResponseEntity<>(result, HttpStatus.OK);
}
// 处理其他运行时异常
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
Map<String, Object> result = new HashMap<>();
result.put("code", 500);
result.put("message", "系统运行异常,请稍后重试");
result.put("data", null);
return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
3. controller层抛出异常的示例
在业务接口中,遇到不符合业务规则的情况,可以直接抛出自定义异常,由全局异常处理器统一捕获处理。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/user/get")
public Map<String, Object> getUser(@RequestParam Integer userId) {
if (userId == null || userId <= 0) {
// 参数不合法时抛出业务异常
throw new BusinessException(400, "用户ID必须为正整数");
}
// 模拟查询用户逻辑
Map<String, Object> user = new HashMap<>();
user.put("id", userId);
user.put("name", "测试用户");
return user;
}
}
前端JavaScript异常处理实现
1. 使用fetch调用接口并处理异常
前端使用fetch API调用Spring接口时,需要同时处理网络错误和业务异常两种情况。
// 封装接口请求方法
function getUserInfo(userId) {
fetch(`http://ipipp.com/user/get?userId=${userId}`)
.then(response => {
// 先判断响应状态码,网络层面的错误会进入catch
if (!response.ok) {
throw new Error(`网络请求失败,状态码:${response.status}`);
}
return response.json();
})
.then(data => {
// 判断后端返回的code,区分业务是否成功
if (data.code === 200 || data.code === undefined) {
// 接口调用成功,处理返回的用户数据
console.log("获取用户信息成功:", data);
} else {
// 后端返回业务异常,提示用户
alert(`操作失败:${data.message}`);
}
})
.catch(error => {
// 捕获网络错误或者前面抛出的错误
console.error("接口调用异常:", error);
alert("网络异常,请检查网络连接后重试");
});
}
// 调用示例
getUserInfo(0);
2. 使用axios调用接口并处理异常
如果使用axios作为请求库,处理方式类似,同样需要判断响应中的业务状态码。
import axios from "axios";
// 创建axios实例
const request = axios.create({
baseURL: "http://ipipp.com",
timeout: 5000
});
// 响应拦截器,统一处理响应
request.interceptors.response.use(
response => {
const res = response.data;
// 假设后端成功响应的code是200,否则都是业务异常
if (res.code !== 200 && res.code !== undefined) {
alert(`操作失败:${res.message}`);
return Promise.reject(new Error(res.message));
}
return res;
},
error => {
// 处理网络错误
console.error("请求错误:", error);
alert("网络异常,请稍后重试");
return Promise.reject(error);
}
);
// 调用接口示例
function getUser(userId) {
request.get("/user/get", {
params: { userId: userId }
}).then(data => {
console.log("用户数据:", data);
}).catch(err => {
// 捕获业务异常或者网络异常
console.error("获取用户失败:", err);
});
}
getUserInfo(-1);
常见注意事项
- 后端返回的异常响应格式需要统一,包括状态码、提示信息、数据字段,避免前端处理时逻辑混乱。
- 敏感异常信息不要直接返回给前端,比如数据库报错信息、服务器路径等,需要做脱敏处理。
- 前端捕获异常后,不要直接把后端返回的错误信息全部展示给用户,可以根据code映射友好的提示文案。
- 如果是跨域场景,需要确保Spring后端配置了跨域支持,否则前端无法正常接收接口的响应。
JavaScriptSpring异常处理前后端交互修改时间:2026-06-13 05:36:36