bigweld86
6 months ago
795
2
General

Bubbling up exceptions

Posted 6 months ago by bigweld86

Hi.

I've got a Controller which extends a custom BaseController. My BaseController has these two methods (among others):

public function sendResponse(array $result, string $message = 'Success') : JsonResponse
    {
        $response = [
            'success' => true,
            'data'    => $result,
            'message' => $message
        ];

        return response()->json($response, 200);
    }

    public function sendError(
        string $error, 
        array $errorMessages = [], 
        int $code = 404) : JsonResponse
    {
        $response = [
            'success' => false,
            'message' => $error
        ];

        if (!empty($errorMessages)) {
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);

    }

So when any of my methods in my controllers resolves successfully then I call sendResponse otherwise sendError.

I've got this method in my controller:

public function edit($id) : JsonResponse
    {
        
            try {
                $attribute = $this->attribute->findAttributeById((int)$id);
                return $this->sendResponse([$attribute]);
        } catch (ModelNotFoundException $e) {
                return $this->sendError($e->getMessage());
        }

    }

and findAttributeById is:

public function findAttributeById(int $id) {
    try {
            return $this->model->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            throw new ModelNotFoundException('Record not found');
        }

the issue is that throwing the error from findAttributeById is not being caught by the edit method. How can I achieved that?

Thanks

Please sign in or create an account to participate in this conversation.