温馨提示×

SpringBoot中怎么处理错误和异常

小亿
83
2024-04-09 17:33:41
栏目: 编程语言

在Spring Boot中,可以通过以下几种方式来处理错误和异常:

  1. 使用@ControllerAdvice注解来定义全局异常处理类,可以在该类中定义各种异常处理方法,如处理特定异常类型的方法、处理所有异常的方法等。
@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
    }
}
  1. 使用@ExceptionHandler注解来处理特定Controller中的异常,可以在Controller中定义多个@ExceptionHandler方法来处理不同类型的异常。
@RestController
public class MyController {
    
    @RequestMapping("/test")
    public String test() {
        throw new RuntimeException("Test exception");
    }
    
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
    }
}
  1. 使用@ControllerAdvice注解来定义全局错误处理类,可以在该类中定义各种错误处理方法,如处理特定错误类型的方法、处理所有错误的方法等。
@ControllerAdvice
public class GlobalErrorHandler {
    
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found: " + e.getMessage());
    }
}
  1. 使用ErrorController接口来定义自定义错误页面,可以根据需要自定义错误页面的展示方式和内容。
@Controller
public class MyErrorController implements ErrorController {
    
    @RequestMapping("/error")
    public String handleError() {
        return "error";
    }
    
    @Override
    public String getErrorPath() {
        return "/error";
    }
}

通过以上方式,可以灵活地处理Spring Boot应用中的错误和异常,提高应用的健壮性和用户体验。

0