MerryChristmas's avatar

Can I move try{}catch{} blocks out of Controller?

Basic Controller with 3 methods. And each method has TryCatch block. Would it be possible not to repeat TryCatch block in each method but keep the functionality the same?

(for example, if FormController extends Controler than move TryCatch over there and now every methods that extends Controller is wrapped inside this specific TryCatch ... something like that)

class FormController
{

    public function createForm()
    {
        try {

            //code
            
        } catch (Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'There was an error.'], 500);
        }
    }
    
    public function deleteForm()
    {
        try {

            //code
            
        } catch (Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'There was an error.'], 500);
        }
    }
    
    public function modifyForm()
    {
        try {

            //code
            
        } catch (Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'There was an error.'], 500);
        }
    }
}

Becomes this:

class FormController
{

    public function createForm()
    {
        // code
    }
    
    public function deleteForm()
    {
        // code
    }
    
    public function modifyForm()
    {
        // code
    }
}

But if // code throws exception it still executes response()->json(['status' => 'error', 'message' => 'There was an error.'], 500)

0 likes
13 replies
tykus's avatar

Your Response is the same regardless the Exception? What Exception might be thrown; is it generic, or something specific?

The Exception Handler would be a location to handle Exception(s) - check out app/Exceptions/Handler.php; or otherwise, if these are your own custom Exceptions; you can make them renderable

MerryChristmas's avatar

@tykus But I would still need to catch that custom Exception in my controller, in each method, no?

tykus's avatar

@MerryChristmas no. The Exceptions will bubble up to the Exception Handler if you do not use the try/catch approach. Then, you can centralize how specific (or all) Exceptions are handled; with a standard Response if needed.

Snapey's avatar

Is it really necessary to have try-catch on every method?

MerryChristmas's avatar

@Snapey For example if you're doing backend for ReactJS I think it would be nice to have try-catch in every method so you can guarantee success/error message in agreed format no matter what. Then it would be necessary.

PovilasKorop's avatar

@MerryChristmas you could standardize the error message in agreed format in one place, in Laravel settings of Error Handling, read the docs about it.

Usually, try-catch is used when you want to catch a SPECIFIC exception and perform some SPECIFIC action on catch.

NoLAstNamE's avatar

Create a middleware ExceptionHandlingMiddleware

class ExceptionHandlingMiddleware
{
    public function handle($request, Closure $next)
    {
        try {
            return $next($request);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => 'There was an error.'], 500);
        }
    }
}

Add the new middleware to your Kernel.php file

'web' => [
    // ... other web middleware
    \App\Http\Middleware\ExceptionHandlingMiddleware::class,
],
4 likes
MerryChristmas's avatar

@NoLAstNamE If this really works this would be very good solution. Being able to apply it only on some routes. Will try it.

jaseofspades88's avatar

What type are you doing in each of these try catch blocks? Are you using already simple Laravel features such as, creating/saving models? In my experience there's little reason to need to wrap these at a controller level as Laravel's exceptions are handled in a much smarter way.

@povilaskorop has directed you to the exact perfect documentation you need above

Please or to participate in this conversation.