How to call custmo error in controller, that after to show in template?
For example, I have condition:
if($id == 500){
// call error
}
If you want to call just the error in the controller and abort, you do
abort(500, 'Internal error');
If you want to return an error
return redirect()->back()->withErrors(['error' => 'was 500']);
You can do this by catching the error in the Handler (app/Exceptions/Handler.php), something like this:
public function render($request, Exception $e){
// other errors here by your wish
// custom error message
if ($e instanceof \ErrorException) {
return response()->view('errors.500', [], 500);
}else{
return parent::render($request, $e);
}
return parent::render($request, $e);
}
Note that you need 500 template in resources/views/errors/500.blade.php (create if it doesnt exist, and fill if with your data or iformation about the exception)
Related
On laravel 9 site in my custom class method raise custom error with error message
<?php
class CustomClass
{
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Exceptions\HttpResponseException;
...
public function method(): array
{
if(false) {
throw new HttpResponseException(response()->json([
'message' => $validated['message'],
], 422));
}
but I failed to catch this error in control where methods raised :
{
try {
$imageUploadSuccess = $customClass->method(
...
); // This method can raise different types of exception
}
catch (ModelNotFoundException $e) { // exception with invalid id is catched - THIS PART WORKS OK
return response()->json([
'message' => 'Item not found',
], 404);
}
catch (HttpResponseException $e) { // I catch HttpResponseException with is generated in method
// None of these 2 methods returns custom error message in method :
\Log::info($e->getMessage()); // empty value - I NEED TO GET THIS MESSAGE TEXT
\Log::info($e->getCode()); // 0 value
\Log::info($e->getTraceAsString());
return response()->json([
'message' => $e->getMessage(),
], 422);
}
return response()->json(['success' => true], 400);
Have I to use other class, not HttpResponseException ? I which way ?
Thanks in advance!
You’re not throwing your custom exception so it’s never raised so it won’t be catchable.
Replace where you throw the HttpResponseException with your Exception.
<?php
class CustomClass
{
public function method()
{
$isValid = false;
if(!$isValid) {
throw new SomeCustomException(response()->json([
'message' => $validated['message'],
], 422));
}
}
}
You would then use do something like:
$customClass = new CustomClass();
$customClass->method();
Note how I have defined a variable $isValid and how I check it for a true or false value in the if statement. This is because if checks for truthy values and false will never be `true so your custom exception would never be thrown.
if (false) {
// code in here will never execute
}
I created an exception called invalid balance, and I'm using like the following. My output result status is 500. How can I change this status to 400?
try {
$balance = Wallet::findOrFail()->docs()
->sum('amount');
if ($balance == 0) {
throw new InvalidBalance();
}
} catch (QueryException $e) {
$message = Str::contains($e->getMessage(), 'Deadlock') ?
'Server is busy' : $e->getMessage();
throw new HttpException(400, $message);
} catch (\Exception $e) {
throw $e;
}
You can use the abort helper.
if ($balance === 0)
{
abort(400, 'Bad Request.');
}
Or within the InvalidBalance class do the abort there.
You can use response() method and pass the http status code as the second parameter as in laravel helpers functions
return response()->json(['message'=>'your message'], 400);
For example, I use:
return User::findOrFail($id);
When row does not exist with $id I get exception.
How I can return this exception in Json response? It returns HTML Laravel page now.
I need something like as:
{"error", "No query results for model"}
From their documentation:
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
So, you can either catch that exception, or go with the simple Find method. It will return false if not found, so you can handle it accordingly.
return User::find($id);
UPDATE:
Option 1:
try {
return User::findOrFail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return json_encode(['error' => 'No query results for model']);
}
Option 2:
$user = User::find($id);
if($user) {
return $user;
}
return json_encode(['error' => 'No query results for model']);
You can handle various types of exceptions, that exception can be handle with a ModelNotFoundException in this case
try{
$user = User::findOrFail($id);
}catch(ModelNotFoundException $e){
return response()->json(['error' => 'User not found'], 400);
}
And there's another way to catch various types of exceptions in the Handler.php located on app/Exceptions/Handler.php there you can catch the exceptions and return whatever you want inside the render function.
For example insede that function you can add this before the return parent::render($request, $e):
if($e instanceof ModelNotFoundException)
{
return new Response(['message' => 'We haven\'t find any data'], 204);
}
You should look in render method of Handler file. You can test exception class here and depending on it return different response in Json format
I'm new to Lumen and want to create an app with this framework. Now I have the problem that if some user enters a wrong url => http://www.example.com/abuot (wrong) => http://www.example.com/about (right), I want to present a custom error page and it would be ideal happen within the middleware level.
Furthermore, I am able to check if the current url is valid or not, but I am not sure how can I "make" the view within the middleware, the response()->view() won't work.
Would be awesome if somebody can help.
Seeing as errors are handled in App\Exceptions\Handler, this is the best place to deal with them.
If you are only after a custom 404 error page, then you could do this quite easily:
Add this line up the top of the Handler file:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Alter the render function to look like so:
public function render($request, Exception $e)
{
if($e instanceof NotFoundHttpException){
return response(view("errors.404"), 404);
}
return parent::render($request, $e);
}
This assumes your custom 404 page is stored in an errors folder within your views, and will return the custom error page along with a 404 status code.
You may want to add this so that when for example blade blows up the error page hander will not throw a PHP error.
public function render($request, Exception $exception)
{
if (method_exists('Exception','getStatusCode')){
if($exception->getStatusCode() == 404){
return response(view("errors.404"), 404);
}
if($exception->getStatusCode() == 500){
return response(view("errors.500"), 404);
}
}
return parent::render($request, $exception);
}
I am using Lumen 8.x version and below solution worked for me:
File path: ▸ app ▸ Exceptions ▸ Handler.php
public function render($request, Throwable $exception)
{
// start custom code
if($exception->getStatusCode() == 404){
return response(view("errors.404"), 404);
}
if($exception->getStatusCode() == 500){
return response(view("errors.500"), 404);
}
// end custom code
return parent::render($request, $exception);
}
Do not forget to create errors folder at /resources/views/errors and create the below 2 new files in errors folder:
404.blade.php
500.blade.php
and add html tags and messages in those files what you want to add.
Happy to help you. Thanks for asking this question.
I faced the same situation. response(view("errors.404"), 404)did not work for me, so I changed it as follows:
public function render($request, Exception $exception)
{
if($exception instanceof NotFoundHttpException){
return response(view('errors.404')->render(), 404);
}
return parent::render($request, $exception);
}
I want to set different view blade template for different exception and also pass the errors on the following page. I tried out the following code but it's not working. It always goes to the else portion of the code and run the parent::render($request, $e);code.
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
if($e instanceof InvalidArgumentException)
{
return response()->view('front.missing', [], 404);
}elseif($e instanceof ErrorException){
return response()->view('front.missing2', [], 404);
}
return $this->renderHttpException($e);
}else{
if($e instanceof InvalidArgumentException)
{
return response()->view('errors.204', []);
}
return parent::render($request, $e);
}
}
Where is the problem here and what I will do now?
InvalidArgumentException is not a child class of HttpException, so it always goes to the else portion.