@ExceptionHandler(value = ApiException.class) 注解详解 - Spring Boot 异常处理
@ExceptionHandler(value = ApiException.class) 注解用于指定处理特定异常类型的方法。当发生 ApiException 异常时,会调用被注解的方法来处理该异常。通常,我们会在控制器类中定义一个方法,并使用 @ExceptionHandler 注解来处理不同类型的异常。这样,当控制器中的其他方法抛出指定的异常时,就会由被注解的方法来处理该异常,返回相应的结果。示例代码:\njava\n@RestController\npublic class MyController {\n \n @ExceptionHandler(value = ApiException.class)\n public ResponseEntity<String> handleApiException(ApiException ex) {\n // 异常处理逻辑\n return new ResponseEntity<>("Api Exception: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);\n }\n \n @GetMapping("/example")\n public String example() throws ApiException {\n // 业务逻辑,可能会抛出 ApiException\n throw new ApiException("Something went wrong");\n }\n}\n\n在上述示例中,如果在 example() 方法中抛出 ApiException 异常,就会被 handleApiException() 方法捕获并处理。handleApiException() 方法会返回一个包含异常信息的 ResponseEntity 对象,并指定 HTTP 状态码为 500。
原文地址: https://www.cveoy.top/t/topic/qcpo 著作权归作者所有。请勿转载和采集!