I am new in zendframework. I am using apigility for rest services and ApiProblemListner to return the response if any error occures.
I have one function in model and this function just through an exception using php exception to use in catch block
I am using model function as the utility function in controller to catch those Exception. While catching exception I am using as
try{
imageUploade(); // this function in model and throwing exception if any error
}catch(\Exception $e){
return new ApiProblemResponse(new ApiProblem(500 , $e->getMessage()));
}
if imageUploade() throw an exception if the image size is more then I am able to catch the exception in catch block. I tried echo $e->getMessage(); and its printing the exception bt if I use new ApiProblem(500 , $e->getMessage()) it is not retuning the json error response with the 500 message. It is returning nothing. even it is not showing any error.
Seems like it is unable to render the error with this class. I am not sure if any event needs to add.
I have tried to search for documents but unable to find it.
Thanks in advance.
Normally it should work if you return an ApiProblemResponse straight from a controller action.
Are you sure your Api-Problem module is active?
Try once like this:
<?php
Application\Namespace;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
class IndexController
{
/**
* #return ApiProblemResponse
*/
public function indexAction()
{
return new ApiProblemResponse(new ApiProblem(500, 'test'));
}
}
If that doesn't work then I think your Api-Problem module is not running or the exception is never caught.
Related
I've searched a few questions for a reason my code is not throwing an error correctly, but I can't figure it out.
I have the following function in my controller
<?php
public function suspend($id)
{
try {
$this->collection = $this->class::find($id);
$this->collection->delete();
return $this->respond_with_success();
} catch (\Exception $e) {
return $this->respond_with_error('Failed to suspend resource with id: ' . $id);
}
}
For reference, I'm using soft deletes. I can suspend a resource once no problem. If I try to suspend one that's already suspended, Laravel correctly throws a 500 as I can see in the log file /storage/logs/laravel.log
This is part of the error I see;
local.ERROR: Call to a member function delete() on null....
Without using
withTrashed() in the query, a row quite obviously cannot be found. So this makes sense.
Great...so why does my catch not actually catch anything? I see a 500 error in the browser, but my application should allow me to continue and handle that error correctly. But it just falls over completely...
The respond_with_error function is below. I've tried changing the $code to 200 in testing, but this doesn't change anything. I've tested returning a simple string rather than with this function to no avail, so I don't think there's anything wrong with this part.
<?php
protected function respond_with_error($message = 'error', $code = 500)
{
return Response::json([
'success' => false,
'message' => $message,
], $code);
}
I'm running Laravel 5.6.29
There are two ways to address this. The first thing to note is ERROR: Call to a member function delete() on null is not an exception, it is a fatal error.
You can use findOrFail instead of find to throw an Exception when the model is not found and that will work.
You could also catch Throwable instead of Exception to catch errors and exceptions (as of PHP7) or just Error to catch errors.
As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.
Read more on PHP7 Error Handling here: http://php.net/manual/en/language.errors.php7.php
I am working on the development of a centralized authentication web app with Symfony 3.4 and I encounter a problem with the auto-management of exception that Symfony provides. The problem is that I want to catch a ConnectionException raised by the LDAP component when the connexion to the Active Directory fails. The objective is to use this exception to notice when it fails and to redirect to a specific page. But at the very moment when the Exception is raised by the LDAP component, Symfony notice a kernel.exception event and then render a debug exception page instead of letting the program go and catch the exception.
How could I do to fix that problem and be sure that the Exception is caught and use by my code and not automatically by Symfony ?
I join you the sample of code and the page rendered:
<?php
namespace App\Utils;
use App\Entity\User;
use Symfony\Component\Ldap\Ldap;
use Symfony\Component\Ldap\Exception\ConnectionException;
class ActiveDirectoryStuff
{
private $domain = 'myDomain';
private $ldapString = 'ldap://';
public function __construct()
{}
public function connection($username, $password)
{
try {
$dn = $username.'#'.$this->domain;
$ldap = Ldap::create('ext_ldap', array(
'connection_string' => $this->ldapString . $this->domain,
));
$ldap->bind($dn, $password); //where the ConnectionException is raised
return $ldap;
} catch (\ConnectionException $ce) {
throw $ce;
}
}
}
Image of the Page Rendered Automatically
You're catching the exception, doing nothing then throwing, this is the same as having no try catch at this level of code
Based on what you said use your framework to redirect to a specific page from within the catch and any other logic you want to run when this error happens, then remove throw $ce; that will stop the default error handler from running which I assume is Symfony's
So I want to cover all posible and unexpected errors (like 401, 404, 500) with just one view. I want the same view to show up on all possible errors. I came up with a solution - to copy/paste the same code and just name the views with different error codes. But that seems stiff and wrong. Is there a better way of achieving this?
In the file app/Exceptions/Handler.php you can change what happens when an exception is thrown. In particular there's a render method in there that you can use to catch all the exceptions in an application.
public function render($request, Exception $e)
{
// Handle your error here. Perhaps you can show a view
// when a condition is met. Anything that isn't caught
// here will be handled by Laravel with the
// parent::render call below
return parent::render($request, $e);
}
The parent::render($request, $e) is where Laravel would normally show it's exception/oops page. So by overriding this method you can catch all application errors, including 404, 401 etc.
A cleaner way to achieve this effect is by modifying Laravel's exception handler.
Modify App\Exceptions\Handler to catch every error and return your shared custom error page.
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof NotFoundHttpException) {
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $e);
}
Some customization may be required to fully meet exactly what & how you want data passed to your shared custom view.
Pass the error code to your view on the handler, and display the code on your page, use a switch to handle all the messages depending on the error code.
You can create one unique view (default to 404 error), use try catch in your code to capture other errors and call to this view with parameters so you can change the 404 default error to other error.
I am trying to implement exception handling in my application. For this Laravel framework has its own mechanism to handle the exception using report and render method. But to implement exception I need to track the source from where the exception has been raised e.g. specific page, route etc. For this I need to pass the url to report and render method but unable to do so. What needs to be done in order to implement this in below report and render function.
public function report(Exception $e)
{
parent::report($e);
}
public function render($request, Exception $e)
{
/* Token mismatch Exception handler start */
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return response()->view('errors.sessionExpire', [], 500);
}
/* Token mismatch Exception handler start */
return parent::render($request, $e);
}
As you can see from your own example, you have an instance of Request in the argument list. And Request has all request-specific details like current route, URL and so on.
$request->url(); // Current request URL
$request->fullUrl(); // With query parameters
$request->route(); // Get the route closure for this request path
You can also create your own exception classes that accept as many parameters as you wish!
And the less comfortable way already mentioned – you could go through the exception trace.
You need to use Exception::getTrace
var_dump($e->getTrace());
above line will give you all details regarding exception.
public function report(Exception $e){
echo '<pre>'; // add this line
print_r($e->getTrace()); // add this line
parent::report($e);
}
I followed a tutorial and looked Laravel's docs for registering a custom error handler.
I register the class, and throw MyCustomException, but for some reason, it ignores everything in it and just runs the regular Exception class. The code below prints out exception 'MyCustomException' with message 'This is NOT the message I want to see' instead of "This is the custom exception message"
Currently all the code below is just on a test page, but I've tried registering the class (and putting the MyCustomException declaration) into global.php before Exception and I've tried after Exception as well. Nothing changes.
I've tried sleep(10) inside of MyCustomException too, and that doesn't get run; MyCustomException just doesn't get run.
What am I doing wrong?
Edit: in fact, copying and pasting the code from the tutorial results in the same thing as my custom code; the custom exception handler doesn't get run.
class MyCustomException extends Exception {}
App::error(function(MyCustomException $exception) {
return "This is the custom exception message.";
});
//Now throw the error and see what comes out
try {
throw new MyCustomException('This is NOT the message I want to see');
} catch (MyCustomException $e) {
die($e);
}
please try like this
throw new MyCustomException('This is NOT the message I want to see');
You've probably solved this by now, but what you want is $e->getMessage().
With PHP 5.1+ that will print your exception message.
Docs: http://php.net/manual/en/exception.getmessage.php