Search code examples
laravelapi-design

How to properly return multiple errors from multiple functions in the main function?


I have here a function for an endpoint where I create a customer. It goes like this:

public function createCustomer (Request $request){
    // Store customer's basic information ...
    $customer = $this->clientCustomerepository->createCustomer([$request])

    if($customer->customer_id){ 
        $this->saveCustomerAdditionalDetails($customer->customer_id, $request);

        if ($request['is_third_party'])
            $this->createThirdParty($customer->customer_id, $request);

        // return API response ...
        return APIResponse::format(201, 'success', 'Customer has been created', $customer, null);
    }
    else
        // return API response ...
        return APIResponse::format(400, 'failed', 'Bad Request', null);
}

If it fails in during storing the customer's basic information, the API returns an error message

But if it didn't whether the saveCustomerAdditionalDetails() failed or not the API should proceed to the next line, in this case checking if 'is_third_party' is enabled, if so then call createThirdParty() function.

Currently, as long as storing the customer's basic information is successful the API returns a success response together with the customer's basic information. In this case the API consumer is not notified that somewhere in saveCustomerAdditionalDetails() or createThirdParty(), one of those processes failed.

What is the proper error message if one or both functions $this->saveCustomerAdditionalDetails($request) and $this->createThirdParty($request) failed?


Solution

  • Method 1: Return an error if any method fails and inform the user in response what he/she has to do to fix the error. Also, use the firstOrCreate method to create a customer. firstOrCreate. it will do both actions find or create customer. ` $errors = [];

        try {
            $this->saveCustomerAdditionalDetails($customer->customer_id, $request);
        } catch (\Exception $e) {
            $errors[] = 'Failed to save customer additional details.';
        }
    
        if ($request['is_third_party']) {
            try {
                $this->createThirdParty($customer->customer_id, $request);
            } catch (\Exception $e) {
                $errors[] = 'Failed to create third party.';
            }
        }
    
        if (!empty($errors)) {
            return APIResponse::format(201, 'partial_success', 'Customer has been created with some errors', $customer, $errors);
        }`
    

    Method 2: Use Database Transactions. you can undo the previous database transactions Laravel Database Transactions

    DB::beginTransaction();
    
       try {
            DB::insert(...);
            DB::update(...);
            DB::delete(...);
    
            DB::commit();
       } catch (\Exception $e) {
            DB::rollback();
       }