I am using Laravel 5.6. I have created a custom exception class that handles the error without any issue if the error occurs in a controller function, model function, or helper function. However, it doesn't work when I call the method the same method from a blade file.
I have a helper function getConfigValue($key). It throws CustomException when a value is not found. If I call this method from a controller method then the CustomException thrown by the getConfigValue helper function is handled as expected. But If I call this method in a blade file then Laravel's default handler is called which shows the exception class to be ErrorException. However, the error message is the same as passed to the CustomException class constructor by the getConfigValue method. It seems Laravel is converting CustomException thrown by helper function to ErrorException when called from a blade file.
Here's my CustomException class
namespace App\Exceptions;
use Exception;
class CustomException extends Exception {
public $error_code;
public $error_message;
public function __construct($error_code, $error_message) {
parent::__construct($error_message);
$this->error_code = $error_code;
$this->error_message = $error_message;
}
public function render($request) {
if (php_sapi_name() === 'cli') {
echo $this->getMessage();
return;
} else if($request->ajax()) {
return response()->json([
'success' => false,
'message' => $this->getMessage()
], $this->error_code);
} else {
session()->flash('error', $this->getMessage());
return redirect()->back();
}
}
}
Here's the helper function
function getConfigValue($key) {
$repo = new \App\Repositories\ConfigRepo;
return $repo->getVal($key);
}
In ConfigRepo I have getVal function like:
function getConfigValue($key) {
$data = json_decode(file_get_contents('config.json'), true);
if (!isset($data[$key])) {
throw new \App\Exception\CustomException("$key not found, Pls do _____ to fix the error.");
}
return $data[$key];
}