Laravel store exception in database

Mohit Mehta
2 min readFeb 15, 2019

--

For bug free system we must look into every exceptions. In multi user system it’s hard to keep track on every exceptions. So here is a method by which you can store every exceptions in database.

Step 1. Create a new table with columns (user_id, action, exception and timestamps)

Step 2. Create New model for above table. For example I am giving name DbLog.

Step 3. Create new exception handler LogData.php and paste below code.

app/Exceptions/LogData.php

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Support\Facades\Auth;
use App\DbLog;
class LogData extends Exception
{
/**
* Report the exception.
*
* @return void
*/
public function report(){
}

/**
* Render the exception into an HTTP response.
*
* @param \Illuminate\Http\Request
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception){
$log = new DbLog;
$log->user_id = Auth::user()->id;
$log->action = $request->fullUrl();
$log->exception = $exception;
$log->save();
return \Redirect::back()->with('error', 'Something Went Wrong.');
}
}

Here render function will store each exception in our table with user id of current logged in user. Action column will have complete url of page/method where exception occurred. After storing exception it will return on same page with error message. So user will see only error message instead of whole exception.

Step 4. Edit “render” function of Handler.php.

app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
if ($exception instanceof \App\Exceptions\LogData) {
return $exception->render($request, $exception);
}
return parent::render($request, $exception);
}

Here we have checked if exception is type of LogData (which we’ll throw in next step) then it will pass request to handler.

Step 5. Now we can use this exception handler anywhere with try catch block. Below is the example.

try{
// your code goes here...
}catch (\Exception $e) {
throw new \App\Exceptions\LogData($e);
}

So now you can check how is your system working.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mohit Mehta
Mohit Mehta

Written by Mohit Mehta

Full stack enthusiastic developer

No responses yet

Write a response