squareboat / sneaker

An easy way to send emails whenever an exception occurs on server.
MIT License
222 stars 46 forks source link

Problem in catch when the return is json response #19

Closed sobhanatar closed 6 years ago

sobhanatar commented 6 years ago

Hi I have this code:

public function index(): JsonResponse
{
    try {
        //make some error
       return response()->json(['data' => $data]);
   } catch (Exception $e) {
        return response()->json(['message' => trans('code_execution_fail', ['e' => $e->getCode()])], 422);
   }
}

I set capture to '*' so it get all exceptions. But it doesn't call report function in this context although when I use a function like abort(404, 'message') it executes sneaker in report function and send email to my inbox.

What I'm missing?

sobhanatar commented 6 years ago

Hi I dig dipper and I understood that by returning json response no exception throws like the function abort() do. So I changed my code to something like this and add finally to email the exception.

public function index(): JsonResponse
{
    try {
        //make some error
       return response()->json(['data' => $data]);
   } catch (Exception $e) {
        app('sneaker')->captureException($e);
        return response()->json(['message' => trans('code_execution_fail', ['e' => $e->getCode()])], 422);
   }
}

But this way I have to add app('sneaker')->captureException($e); to all my catch blocks. Is there any better way for that?

akaamitgupta commented 6 years ago

@sobhanattar Ideally your App/Exceptions/Handler@report should be called for each exception but here you are catching each exception by try {} catch {} so this is the only solution I can see.

sobhanatar commented 6 years ago

@akaamitgupta I found a new solution for this problem, although the change in catch is still a necessity but I'm using a helper method report($e) which is short and this way If I want to do some change in the behavior of types of emails and such a things I shouldn't go back and put all that logic in every catch blocks which is a + for me.

Now my code is like this:

public function index(): JsonResponse
{
     try {
        //make some error
       return response()->json(['data' => $data]);

     } catch (Exception $e) {
        report($e);
        return response()->json(['message' => trans('code_execution_fail', ['e' => $e->getCode()])], 422);
     }
}

I think it's not bad to change the Doc to mention this :-)