简体   繁体   English

如何使用通用异常处理程序捕获异常?

[英]How to catch exceptions using a general exception handler?

I have this code in which I make a request to the service, if there is no department with that id, my method in the service class will throw a custom exception which I catch in the method from this controller, when I catch the exception, I return a response entity with the error message and HTTP status to the endpoint.我有这段代码,我在其中向服务发出请求,如果没有具有该 ID 的部门,我在服务类中的方法将抛出一个自定义异常,当我捕获异常时,我会在该控制器的方法中捕获该异常,我将带有错误消息和 HTTP 状态的响应实体返回到端点。 I was informed that I don't need to catch the exception here, I just need to catch it in general exception handler.我被告知我不需要在这里捕获异常,我只需要在通用异常处理程序中捕获它。 Right now I don't understand what that means.现在我不明白那是什么意思。

 @GetMapping("/departments/{departmentId}")
    public ResponseEntity<Object> getDepartmentById(@PathVariable("departmentId") Long departmentId) {
        DepartmentDTO departmentDTO = null;
        logger.debug("Entering get item by id endpoint");
        try {
            departmentDTO = departmentService.getDepartmentById(departmentId);
            logger.info("Returned department with id: " + departmentId);
        } catch (ApiException e) {
            logger.error("Unable to return department with ID: " + departmentId + " ,message: " + e.getMessage(), e);
            return GeneralExceptionHandler.handleExceptions(e);
        }
        return ResponseEntity.ok().body(departmentDTO);

    }

this is my exception handling class这是我的异常处理类

@ControllerAdvice
public class GeneralExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GeneralExceptionHandler.class);
    @ExceptionHandler(value = {ApiException.class})
    public static ResponseEntity<Object> handleExceptions(ApiException e) {
        logger.info("Exception handled:"+e.getMessage()+" with http status: "+e.getHttpStatus());
        return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
    }
}

To use a general exception handler, you can remove the try-catch block in your controller method and just let the exception be thrown.要使用通用异常处理程序,您可以删除控制器方法中的 try-catch 块,只让异常被抛出。 The exception will then be caught by the @ExceptionHandler method in your GeneralExceptionHandler class.然后异常将被 GeneralExceptionHandler 类中的 @ExceptionHandler 方法捕获。

Your controller can be simplified to the following:您的控制器可以简化为以下内容:

@GetMapping("/departments/{departmentId}")
public ResponseEntity<Object> getDepartmentById(@PathVariable("departmentId") Long departmentId) {
    logger.debug("Entering get item by id endpoint");
    DepartmentDTO departmentDTO = departmentService.getDepartmentById(departmentId);
    logger.info("Returned department with id: " + departmentId);
    return ResponseEntity.ok().body(departmentDTO);
}

If a ApiException is thrown in the departmentService.getDepartmentById method, it will be caught by the @ExceptionHandler method in your GeneralExceptionHandler class, which will log the exception and return a response with the error message and HTTP status code specified in the ApiException.如果在 departmentService.getDepartmentById 方法中抛出 ApiException,它将被您的 GeneralExceptionHandler 类中的 @ExceptionHandler 方法捕获,该方法将记录异常并返回包含 ApiException 中指定的错误消息和 HTTP 状态代码的响应。

This way, you can centralize the exception handling logic in your GeneralExceptionHandler class and avoid duplicating the exception handling code in multiple controllers.这样,您可以将异常处理逻辑集中在 GeneralExceptionHandler 类中,避免在多个控制器中重复异常处理代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 异常处理程序不捕获自定义异常 - Exception Handler does not catch custom exceptions 捕获多个异常的处理程序? - Catch handler for multiple exceptions? Java何时捕获一般异常和特定异常 - Java when to catch general Exceptions and specific Exceptions 在Java中,如果捕获并重新抛出了一般异常,外部方法是否仍然可以捕获特定异常? - In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions? 使用错误页面处理程序捕获休眠异常? - Catch hibernate exceptions with errorpage handler? Java处理程序对象如何捕获所有捕获和未捕获的异常? - How can a Java handler object catch all caught and uncaught exceptions? 在 Java 中使用 Exceptions 专门创建自己的异常如何正确使用 try、catch、finally 命令? - In Java using Exceptions specifically creating own exception how do I properly use the try, catch, finally command? 为什么我的服务默认异常处理程序没有捕获我的服务异常? - Why doesn't my service default exception handler catch my service exceptions? 如何在不使用任何 try 和 catch 异常处理程序的情况下在 android 中工作时解决 NumberFormatException: Empty string? - How to resolve NumberFormatException: Empty string, while working in android without using any try and catch exception handler? 无法在异常处理程序中捕获JsonMappingException - Unable to catch JsonMappingException in Exception Handler
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM