代做广联达 的网站,乐山市城乡规划建设局网站,微信公众号做视频网站,钉钉怎么注册企业在 Spring Boot 应用中实现统一异常处理是非常重要的#xff0c;它可以帮助我们更好地管理和响应应用程序中的错误。通过使用 ControllerAdvice 和 ExceptionHandler 注解#xff0c;我们可以创建一个全局的异常处理器来捕获并处理不同类型的异常。
步骤 1: 创建一个异常处理…在 Spring Boot 应用中实现统一异常处理是非常重要的它可以帮助我们更好地管理和响应应用程序中的错误。通过使用 ControllerAdvice 和 ExceptionHandler 注解我们可以创建一个全局的异常处理器来捕获并处理不同类型的异常。
步骤 1: 创建一个异常处理类
首先我们需要创建一个带有 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;
import org.springframework.web.bind.annotation.ResponseStatus;ControllerAdvice
public class GlobalExceptionHandler {// 处理特定异常ExceptionHandler(value {NullPointerException.class, IllegalArgumentException.class})ResponseStatus(HttpStatus.BAD_REQUEST)public ResponseEntityString handleException(Exception e) {return new ResponseEntity(Error: e.getMessage(), HttpStatus.BAD_REQUEST);}// 处理所有未捕获的异常ExceptionHandler(value Exception.class)ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)public ResponseEntityString handleAllExceptions(Exception e) {return new ResponseEntity(An unexpected error occurred: e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}
}步骤 2: 定义自定义异常可选
有时候你可能需要定义自己的异常类型以便更精确地控制应用的行为。例如
public class ResourceNotFoundException extends RuntimeException {public ResourceNotFoundException(String message) {super(message);}
}然后在你的异常处理类中添加一个新的方法来专门处理这种异常
ExceptionHandler(ResourceNotFoundException.class)
ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntityString handleResourceNotFoundException(ResourceNotFoundException ex) {return new ResponseEntity(ex.getMessage(), HttpStatus.NOT_FOUND);
}步骤 3: 在控制器中抛出异常
在你的控制器中你可以根据业务逻辑的需要抛出这些异常。例如
RestController
public class UserController {GetMapping(/users/{id})public User getUser(PathVariable Long id) {User user userRepository.findById(id).orElse(null);if (user null) {throw new ResourceNotFoundException(User not found with id: id);}return user;}
}总结
通过以上步骤你可以为 Spring Boot 应用程序设置一个强大的异常处理机制。这不仅有助于提高用户体验还可以确保应用程序更加健壮和易于维护。使用 ControllerAdvice 和 ExceptionHandler 是实现这一目标的有效方式。