使用 @restcontrolleradvice 配合 @exceptionhandler 可以统一捕获短信发送异常。核心做法是定义一个处理特定异常类(如 smssendexception)的方法,该方法返回标准的 json 响应结构,从而拦截业务层抛出的错误并转化为 http 响应。

如何定义全局异常处理器类
创建一个被 @RestControllerAdvice 注解的类,并在其中添加 @ExceptionHandler 方法。该方法的参数类型指定为需要捕获的异常类,Spring Boot 会在发生此类异常时自动调用此方法。通过返回 ResponseEntity 对象,可以自定义状态码和响应体内容,确保前端能接收到明确的错误信息。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(SmsSendException.class)
public ResponseEntity<string> handleSmsException(SmsSendException ex) {
return ResponseEntity.status(500).body("短信发送失败: " + ex.getMessage());
}
}</string>
如何在业务代码中抛出异常
在调用短信服务的地方,如果检测到发送失败或网络错误,应手动抛出之前定义的异常类。这样做的目的是将具体的底层错误(如第三方 API 超时)转换为应用层的业务异常,以便全局处理器能够识别并统一处理。通常建议在 Service 层进行这种转换,保持 Controller 层的简洁。

import org.springframework.stereotype.Service;
@Service
public class SmsService {
public void send(String phone, String content) {
try {
// 模拟短信发送逻辑
if (phone == null || phone.isEmpty()) {
throw new SmsSendException("手机号不能为空");
}
System.out.println("Sending SMS to " + phone);
} catch (Exception e) {
throw new SmsSendException("短信发送过程中发生错误", e);
}
}
}
当手机号为空时会触发什么结果
当传入的 phone 参数为空字符串或 null 时,SmsService 会直接抛出 SmsSendException。全局异常处理器捕获到该异常后,会返回状态码 500 以及包含具体错误信息的 JSON 字符串。这验证了异常处理机制在输入校验失败时的有效性,确保了错误的统一出口。











