- 常见异常类型:
NotFoundException
:通常用于表示请求的资源不存在,比如在根据ID查询数据库记录,而该ID对应的记录不存在时可以抛出此异常。
BadRequestException
:表示客户端发送的请求有误,比如请求参数格式不正确等情况。
UnauthorizedException
:当用户未经过身份验证,尝试访问需要授权的资源时抛出。
- 使用
@ControllerAdvice
和@ExceptionHandler
注解处理异常示例代码:
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(NotFoundException.class)
public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND);
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<String> handleBadRequestException(BadRequestException ex) {
return new ResponseEntity<>("Bad request", HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<String> handleUnauthorizedException(UnauthorizedException ex) {
return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
@GetMapping("/example/{id}")
public String getExample(@PathVariable Long id) {
if (id < 0) {
throw new BadRequestException();
}
// 模拟查询数据库,如果没找到则抛出NotFoundException
boolean exists = false;
if (!exists) {
throw new NotFoundException();
}
// 如果需要身份验证,未通过验证可抛出UnauthorizedException
boolean isAuthenticated = false;
if (!isAuthenticated) {
throw new UnauthorizedException();
}
return "Example response";
}
}
public class NotFoundException extends RuntimeException {
public NotFoundException() {
super();
}
public NotFoundException(String message) {
super(message);
}
}
public class BadRequestException extends RuntimeException {
public BadRequestException() {
super();
}
public BadRequestException(String message) {
super(message);
}
}
public class UnauthorizedException extends RuntimeException {
public UnauthorizedException() {
super();
}
public UnauthorizedException(String message) {
super(message);
}
}