【问题标题】:How to handle errors in a Spring-MVC project without if else?如何在没有 if else 的情况下处理 Spring-MVC 项目中的错误?
【发布时间】:2020-08-10 01:08:44
【问题描述】:

我不明白如何处理以下错误:

CustomerService类中我删除了id的客户,如果不存在这样的id,那么一定会报错!没有if else 构造怎么办?

CustomerService:

// Delete customer
    public void deleteCustomer(Long id){
            Customer customer = customerRepository.getByIdAndUserRole(id, "customer");
            customerRepository.delete(customer);
        }

CustomerController:

// DELETE MAPPING
    //
    // Delete customer with ID
    @DeleteMapping("/customers/{id}")
    void deleteCustomer(@PathVariable Long id) {
        customerService.deleteCustomer(id);
    }

【问题讨论】:

    标签: java rest spring-mvc exception


    【解决方案1】:

    如果你想抛出错误,那么你必须检查一个条件,即会有一个 if 语句,但不一定需要 else。

    例如,你可以根据下面的检查删除响应并抛出错误。

    if (deleteCount == 0) {
      //throw error here
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用控制器建议。每当发生异常时,它将由处理程序直接处理。不需要 if/else 或 try/catch 块。

      1) 创建一个类CustomerControllerHandler,用@ControllerAdvice注解。

      2) 现在创建带有异常类型参数的方法。

      3) 这些方法将返回您想要的 JSON/POJO/void。

      4) 使用 @ExceptionHandler(Exception.class) 注释方法和 @ResponseStatus(HttpStatus.BAD_REQUEST),

      @ControllerAdvice
      public class CustomerControllerHandler {
           @ExceptionHandler(Exception.class)
           @ResponseStatus(HttpStatus.BAD_REQUEST)
           public void processException(Exception ex) {
           }
      }
      

      【讨论】:

        【解决方案3】:

        您可以尝试改用this。这是CrudRepositorydeleteById 方法(希望您正在使用它),如果找不到客户,它会抛出IllegalArgumentException

        我假设“错误”的意思是“异常”,然后在控制器中你可以用这样的 try-catch 块包围:

        try{
            customerService.deleteCustomer(id);
        } catch (IllegalArgumentException e) {
            log.error("No customer id exists!", e); 
            // if you have no logger, then use System.out.println() at least
        }
        

        如果您想向调用者返回错误,则将数据类型从 void 更改为 HttpResponse<String>,当捕获异常时您可以 return HttpResponse<>("No customer exists with that id!", HTTP.BAD_REQUEST)。现在调用者将收到一个 400 - bad request。

        更好的方法是在服务本身中捕获异常并将布尔值返回给控制器(true 如果客户被删除,false 如果无法删除/找不到)。

        【讨论】:

        • 这是一个糟糕的方法。值得检查 id is not null 以避免 IllegalArgumentException,因此这里不建议使用 try-catch 块。
        • 这就是 @NotNull 在控制器中的用途。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多