SpringBoot中怎么处理错误和异常

   2024-10-25 6600
核心提示:在Spring Boot中,可以通过以下几种方式来处理错误和异常:使用@ControllerAdvice注解来定义全局异常处理类,可以在该类中定义各

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

使用@ControllerAdvice注解来定义全局异常处理类,可以在该类中定义各种异常处理方法,如处理特定异常类型的方法、处理所有异常的方法等。
@ControllerAdvicepublic class GlobalExceptionHandler {        @ExceptionHandler(Exception.class)    public ResponseEntity<String> handleException(Exception e) {        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());    }}
使用@ExceptionHandler注解来处理特定Controller中的异常,可以在Controller中定义多个@ExceptionHandler方法来处理不同类型的异常。
@RestControllerpublic 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());    }}
使用@ControllerAdvice注解来定义全局错误处理类,可以在该类中定义各种错误处理方法,如处理特定错误类型的方法、处理所有错误的方法等。
@ControllerAdvicepublic 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());    }}
使用ErrorController接口来定义自定义错误页面,可以根据需要自定义错误页面的展示方式和内容。
@Controllerpublic class MyErrorController implements ErrorController {        @RequestMapping("/error")    public String handleError() {        return "error";    }        @Override    public String getErrorPath() {        return "/error";    }}

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

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号