Customize Laravel FormRequest autorize method validation - php

Laravel allows us to authorize, or not, a FormRequest to be processed via the authorize method. If the request isn't authorized, it will throw a \Illuminate\Auth\Access\AuthorizationException exception, with a message:
This action is unauthorized.
Is there somehow to customize this message?
See that I want to customize the message itself. Customizing the error messages of attributes I know it is possible!

To change the message you can add the following to your FormRequest class.
protected function failedAuthorization()
{
throw new AuthorizationException('Your new message goes here.');
}

if you are trying to customise the message authourization exceptional message then use throw new exception in authorization controller itself in else part

Related

Laravel $e->getMessage empty on Request validation error

I'm trying to setup custom error handlers in Handler.php but when I try to get the error message when a Request validation isn't met I get an empty response.
public function render($request, Exception $e)
{
dd($e->getMessage());
return parent::render($request, $e);
}
My rules are set to:
'min:10'
So when I don't provide parameters of length 10 I want it to output that error within $e->getMessage() so I can do whatever I want to do with it, but the error is always empty. What am i doing wrong?
Exception will not give you errors that occurs for Validator.
Validator error are sent on its object and by errors() method. So, after calling the errors method on a Validator instance, you will receive an Illuminate\Support\MessageBag instance, which has a variety of convenient methods for working with error messages.
For more details: https://laravel.com/docs/5.2/validation#custom-error-messages

Symfony2, FOSRestBundle - catch exceptions

I have Symfony application and I use FOSRestBundle with AngularJS. My Symfony application haven't any views.
I want to show in AngularJS messages about information received from server, with ngToast module.
If I create something or update it it's easy to show. But If server throw some exception? For example Angular client trying get item with wrong ID or this user have no acces to do this action? In this case server will throw exception, but I want to show appropriate message.
Can symfony catch this exception and for example translate it to Response object?
For example - if I have no access exception symfony should catch it and make something like this:
return new Response(400, "You don't have permission to acces this route");
and Angular will get:
{
"code": 400,
"message": "You don't have permission to acces this route"
}
Is it possible? How should I do it? Maybe I should do it other way.
I would suggest to go for more FOSRestBundle approach, which is to configure the Exceptions and if should or not show the messages:
fos_rest:
exception:
enabled: true
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': HTTP_FORBIDDEN
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
Lets say you have a custom AccessDeniedException for a certain action, you can create the exception and then put it in the configuration.
<?php
class YouCantSummonUndeadsException extends \LogicException
{
}
Wherever you throw it:
<?php
throw new YouCantSummonUndeadsException('Denied!');
You can configure it:
codes:
'My\Custom\YouCantSummonUndeadsException': HTTP_FORBIDDEN
messages:
'My\Custom\YouCantSummonUndeadsException': true
And get a result like:
{
"code": 403,
"message": "Denied!"
}
I hope this makes it clearer!
Yes of course this is possible. I suggest you implement a simple Exception listener. And make all your exception classes extend a BaseException or implement a BaseException, so you will know which exceptions are from "your" code.
class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
// Do your stuff to create the response, for example response status code can be exception code, and exception message can be in the body or serialized in json/xml.
$event->setResponse($response);
return;
}
}
Register it in the container:
<service id="your_app.listener.exception" class="App\ExceptionListener">
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>

Laravel custom Exception handler not running

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

How can I throw a 403 exception in Symfony2?

I am doing a check if there is a specific token in my request URI and throw a Symfony\Component\Security\Core\Exception\AccessDeniedException if there is no token or the token is wrong.
if(!isset($token) && $token != 'whatever') {
throw new AccessDeniedException('No token given or token is wrong.');
}
But when I use this AccessDeniedException, Symfony2 simply redirects to the login page. Instead, I would like to have a dedicated 403 error page (I already created app/Resources/TwigBundle/views/Exceptions/error403.html.twig file).
What would I have to change in order to achieve this? Do I have to use a PHP native Exception? But how can I tell to pass a 403 error code?
Does Symfony2 maybe have a specific 403-Exception which doesn't simply redirect to login?
Throw Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException.
That will bypass the security system and give you a 403 response which in turn will get picked up by the twig exception listener.
As of Symfony 2.6 you can use the following controller shortcut that will trigger the good exception for you:
return $this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');

Laravel Handle Exceptions

I am using the Stripe API and Laravel together. If Stripe detects an error charging the card (such as using a test credit card number that throws an invalid security code error), the API bindings are supposed to throw an exception, which they do. The problem is, I am having issues catching the exception before Laravel throws up the error 500 page (I am trying to perform a redirect with an error message instead).
The code I've written is available on Pastebin: http://pastebin.com/ZaW2xbbt
The behavior I'm expecting is for the catch to fire and the redirect to be performed, but instead, I get the stack trace with the message and "Unhandled Exception". That's confusing me because I am handling the exception.
Variables such as $customer are valid and have been defined previously. Any ideas what's going on?
For any future viewers, here's an article on error handling in laravel 4.
Laravel 4 lets you catch Exceptions by exception type. For instance, you can handle Symfony's HttpException and of its sub-classes by adding this to your code:
// Catch HttpException, NotFoundHttpException, etc etc
App::error(function(HttpException $exception, $code, $fromConsole)
{
...
});
Symfony HttpExceptions (used in Laravel) can be found here.
You can also throw this in a ServiceProvider:
<?php namespace My\Namespace;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\HttpKernel\Exception\HttpException;
class MyServiceProvider extends ServiceProvider {
public function register()
{
$this->app->error(function(HttpException $exception, $code, $fromConsole)
{
...
});
}
}
Hope that helps!
Generally, all errors logged by Laravel are logged under storage/logs folder
Anyway, the 500 error could be a syntax/parse error, in such case the Laravel framework could be not yet loaded when the error occurs and if so, the exception is not lhandled by Laravel.
In this case you should access the apache/vargrant/whatif php error log in some way (dependently on your server capabilities and configuration), in my personal cases I have configured the server to put that logs in a /storage/logs/error_log.txt file such that I can access them as other Laravel server logs
Note that in Laravel 5, you have app/Exceptions/Handler.php as entry point for customize exception handling/reporting
https://laravel.com/docs/5.7/errors#the-exception-handler

Categories