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?
In Laravel 5 you can catch exceptions by editing the render method in app/Exceptions/Handler. php . 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.
Through your config/app. php , set 'debug' => env('APP_DEBUG', false), to true . Or in a better way, check out your . env file and make sure to set the debug element to true.
The simplest way to catch any sql syntax or query errors is to catch an Illuminate\Database\QueryException after providing closure to your query: try { $results = \DB::connection("example") ->select(\DB::raw("SELECT * FROM unknown_table")) ->first(); // Closures include ->first(), ->get(), ->pluck(), etc. }
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With