spring注解之——@RestControllerAdvice

这篇文章介绍了Spring框架中的@RestControllerAdvice注解在SpringMVC应用中的作用,包括全局异常处理,如何与@ExceptionHandler配合处理不同类型的异常,并以RESTfulAPI格式返回响应。
摘要由CSDN通过智能技术生成
@RestControllerAdvice
是Java中Spring框架提供的一个注解,主要用在Spring MVC应用程序中。它是注释的特殊化@ControllerAdvice

以下是它的作用和使用方法:

  1. 全局异常处理:它允许您以集中的方式处理整个应用程序的异常。当应用程序中的任何控制器方法抛出异常时,@RestControllerAdvice带注释的类可以拦截并处理这些异常。

  2. @ControllerAdvice 和 @ResponseBody 的组合:与@ControllerAdvice通常处理基于视图的控制器不同,@RestControllerAdvice是专门为 RESTful API 设计的。它结合了@ControllerAdvice@ResponseBody,这意味着它不仅拦截异常,而且还以适合 RESTful API(如 JSON 或 XML)的格式直接返回响应,而不需要@ResponseBody在每个处理程序方法上显式注释。

  3. 合并异常处理:通常用于合并异常处理逻辑并减少重复。您可以在用@RestControllerAdvice.

  4. 自定义:您可以@RestControllerAdvice在应用程序中定义多个类来处理不同类型的异常或对相关的异常处理逻辑进行分组。

 

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {NullPointerException.class, IllegalArgumentException.class})
    public ResponseEntity<Object> handleBadRequestException(RuntimeException ex, WebRequest request) {
        // Craft a custom response body
        String responseBody = "An error occurred: " + ex.getMessage();
        
        // Return ResponseEntity with appropriate status code and response body
        return ResponseEntity.badRequest().body(responseBody);
    }

    @ExceptionHandler(value = {NotFoundException.class})
    public ResponseEntity<Object> handleNotFoundException(NotFoundException ex, WebRequest request) {
        // Craft a custom response body
        String responseBody = "Resource not found: " + ex.getMessage();
        
        // Return ResponseEntity with appropriate status code and response body
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseBody);
    }

    // More exception handling methods can be defined here
}
  • @RestControllerAdvice用于将该类标记GlobalExceptionHandler为全局异常处理程序。
  • @ExceptionHandler用于指定每个方法应该处理哪些异常。该handleBadRequestException方法处理NullPointerExceptionand IllegalArgumentException, whilehandleNotFoundException处理NotFoundException
  • 在每个方法中,您可以根据需要自定义响应并返回一个ResponseEntity对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值