Kamil Davudov
Kamil Davudov

Reputation: 363

How to get raw Exception Message without HTML in Laravel?

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?

Upvotes: 8

Views: 35405

Answers (1)

Limon Monte
Limon Monte

Reputation: 54419

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);
}

Upvotes: 22

Related Questions