Home » Php » php – How to get raw Exception Message without HTML in Laravel?

php – How to get raw Exception Message without HTML in Laravel?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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