8

I make ajax requests to Laravel backend.

In backend I check request data and throw some exceptions. Laravel, by default, generate html pages with exception messages.

I want to respond just raw exception message not any html.

->getMessage() doesn't work. Laravel, as always, generate html.

What shoud I do?

1 Answer 1

22

In Laravel 5 you can catch exceptions by editing the render method in app/Exceptions/Handler.php.

If you want to catch exceptions for all AJAX requests you can do this:

public function render($request, Exception $e) 
{
    if ($request->ajax()) {
        return response()->json(['message' => $e->getMessage()]);
    }

    return parent::render($request, $e);
}

This will be applied to ANY exception in AJAX requests. If your app is sending out an exception of App\Exceptions\MyOwnException, you check for that instance instead.

public function render($request, Exception $e)
{   
    if ($e instanceof \App\Exceptions\MyOwnException) {
        return response()->json(['message' => $e->getMessage()]);
    }

    return parent::render($request, $e);
}
Sign up to request clarification or add additional context in comments.

3 Comments

good. but how return response with error? I want to get response through ajax error function.
@KamilDavudov you mean response with specific HTTP code?
@KamilDavudov use the source :) Just add the second parameter, e.g. response()->json($data, 400)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.