面试题答案
一键面试1. 自定义业务异常
首先定义一个自定义业务异常类,通常继承自 RuntimeException
或 Exception
。
public class CustomBusinessException extends RuntimeException {
public CustomBusinessException(String message) {
super(message);
}
}
2. 创建全局异常处理器
使用 @ControllerAdvice
注解定义一个全局异常处理器类,在这个类中定义处理特定异常的方法。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomBusinessException.class)
public ResponseEntity<String> handleCustomBusinessException(CustomBusinessException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
3. 注解说明
@ControllerAdvice
:该注解用于定义全局异常处理类,它会作用于所有被@RequestMapping
注解的控制器方法。@ExceptionHandler
:在异常处理器类中,使用该注解来指定处理的异常类型。其参数为要处理的异常类,如上述示例中的CustomBusinessException.class
。
4. 关键步骤总结
- 定义自定义异常类:继承合适的异常基类,以便区分业务异常与其他系统异常。
- 创建全局异常处理器类:使用
@ControllerAdvice
注解标记该类,表明它是一个全局异常处理器。 - 定义异常处理方法:在全局异常处理器类中,使用
@ExceptionHandler
注解标记方法,并指定要处理的异常类型,在方法内部编写异常处理逻辑,如返回特定的 HTTP 状态码和错误信息等。