spring boot 函数异常处理实现包括:使用 @responsestatus 注解指定异常的 http 状态代码。实现 responseentityexceptionhandler 类以定制异常处理过程。异常处理配置方式:注册 responseentityexceptionhandler 类。为自定义异常配置 @responsestatus 注解。实战案例:使用 @responsestatus 注解处理非整数请求,返回 400 响应并包含错误消息。

在处理函数时,异常处理对于确保应用程序的健壮性和稳定性至关重要。Spring Boot 提供了灵活的异常处理机制,允许开发者定制对不同异常类型的响应。
Spring Boot 函数支持两种主要的异常处理方法:
@ResponseStatus 注解: 此注解允许指定异常应产生的 HTTP 状态代码。例如:@ResponseStatus(HttpStatus.BAD_REQUEST)
public class CustomBadRequestException extends RuntimeException {
// ...
}ResponseEntityExceptionHandler: 这种方法提供对异常处理过程的更精细控制。开发者可以重写 handleExceptionInternal() 方法来定制响应:public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
// ...
return super.handleExceptionInternal(ex, body, headers, status, request);
}
}可以通过以下方式配置 Spring Boot 函数中的异常处理:
ResponseEntityExceptionHandler: 将 CustomResponseEntityExceptionHandler 类添加到 Spring Boot 配置中:@SpringBootApplication
public class MyApplication {
// ...
@Bean
public ResponseEntityExceptionHandler customResponseEntityExceptionHandler() {
return new CustomResponseEntityExceptionHandler();
}
// ...
}@ResponseStatus 注解为自定义异常指定响应状态代码,如下所示:@ResponseStatus(HttpStatus.BAD_REQUEST)
public class CustomBadRequestException extends RuntimeException {
// ...
}考虑以下函数,它接收一个整数并对其进行平方:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SquareController {
@GetMapping("/square")
public int square(@RequestParam int number) {
return number * number;
}
}如果客户机发送一个非整数请求,函数将抛出 NumberFormatException。为了处理这种异常,我们可以使用 @ResponseStatus 注解:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SquareController {
@GetMapping("/square")
@ResponseStatus(HttpStatus.BAD_REQUEST)
public int square(@RequestParam int number) {
return number * number;
}
}现在,当客户机发送一个非整数请求时,函数将返回一个 400(错误请求)响应,并包含错误消息。
以上就是Spring Boot 函数中异常处理的实现和配置的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号