Spring Boot 3.x Rest API统一异常处理最佳实践
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                
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 {
 
    // 处理所有Exception类型的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        // 这里可以记录日志,返回自定义的错误信息等
        return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
 
    // 可以添加更多的异常处理方法,针对不同的异常类型进行处理
}这个代码示例展示了如何在Spring Boot 3.x中创建一个全局异常处理器,用于处理应用程序中发生的所有异常。通过使用@ControllerAdvice注解,我们可以集中处理控制器抛出的异常,而不是在每个控制器方法中重复处理相同的逻辑。这样可以提高代码的模块化和可维护性。
评论已关闭