java 如何处理BadRequestBodyException和未找到资源异常

xzabzqsa  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(174)

我是java世界的新手。在服务层我有这个updateCustomer方法。
我处理异常正确吗?有更好的方法吗?我的方法有什么优缺点吗?

@Override
    public ResponseEntity<String> updateCustomer(String id, Customer customer) throws ResourceNotFoundException, BadRequestBodyException {
        log.info("Updating customer.");

        if(!Strings.isNullOrEmpty(customer.getCustomerName())
                && !Strings.isNullOrEmpty(customer.getCustomerType())){

            Customer existingCustomer =  customerRepository.findCustomerById(id)
                    .orElseThrow(() -> new ResourceNotFoundException("Error: Customer not found for id - " + id));

            existingCustomer.setCustomerName(customer.getCustomerName());
            existingCustomer.setCustomerType(customer.getCustomerType());

            customerRepository.save(existingCustomer);

            return ResponseEntity.ok().body("Customer updated successfully.");
        } else {
            throw new BadRequestBodyException("Error: request body can not be null or empty!");
        }
    }
q8l4jmvw

q8l4jmvw1#

有几件事。
1.我建议服务层不要返回ResponseEntity<T>对象,而是应该返回DTO,或者在您的情况下只返回字符串。
1.对于请求主体验证,也可以在控制器中的请求主体模型上使用@Valid注解,或者如果您想处理验证,则在控制器中而不是在服务中进行。
1.控制器类应负责转换/创建发送到服务器的ResponseEntity<?>
1.在控制器类中,可以使用@ExceptionHandler注解定义方法,并指定如何处理该请求。或者,如果处理的异常是从不同的服务引发的,则可以使用@ControllerAdvice定义类,并在其中指定异常处理方法。
对于您的代码,您应该执行以下操作:

//Controller
@Override
public ResponseEntity<String> updateCustomer(String id, Customer customer)
throws ResourceNotFoundException, BadRequestBodyException {
    if (Strings.isNullOrEmpty(customer.getCustomerName())
        || Strings.isNullOrEmpty(customer.getCustomerType())) {
        throw new BadRequestBodyException("Error: request body can not be null or empty!");
    }
    log.info("Updating customer.");
    return ResponseEntity.ok(customerService.updateCustomer(id, customer);
}

// The below exception handling method can be part of your controller or you can centralise them 
// in class annotated with ControllerAdvice 
@ExceptionHandler(BadRequestBodyException.class)
public ResponseEntity<Object> handleBadRequestBodyException(BadRequestBodyException ex) {
    var response = new HashMap<String, Object>();
    response.put("status", "failure");
    response.put("message", "Request body Validation failed.");
    response.put("detailMessage", ex.getLocalizedMessage());
    return ResponseEntity.internalServerError().body(response);
}

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handle(ResourceNotFoundException ex) {
    var response = new HashMap<String, Object>();
    response.put("status", "failure");
    response.put("message", "Resource not found.");
    response.put("detailMessage", ex.getLocalizedMessage());
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}

//Service
@Override
public String updateCustomer(String id, Customer customer) throws ResourceNotFoundException, BadRequestBodyException {
    log.info("Updating customer.");
    Customer existingCustomer = customerRepository
            .findCustomerById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Error: Customer not found for id - " + id));
    existingCustomer.setCustomerName(customer.getCustomerName());
    existingCustomer.setCustomerType(customer.getCustomerType());
    customerRepository.save(existingCustomer);
    return "Customer updated successfully.";
}

希望这对你有帮助!

相关问题