exceptionlaravel-5.1abort

Laravel 5.1 - Difference between throwing Exceptions and abort()


I've been throwing Exceptions when I wanted to halt an action during backend processing. I had forgotten that I could use the Laravel abort() method. Is there any reason to use abort() over throwing an Exception? Does it pretty much do the same thing?

I'm also asking because I noticed that while I'm tailing my logs, abort() doesn't show the stack trace, but throwing the Exception does. I don't need the stack trace in these cases, because I know why it's failing. I also don't want the logs to grow huge from these known failures.


Solution

  • Let's have a look at the code:

    /**
     * Throw an HttpException with the given data.
     *
     * @param  int     $code
     * @param  string  $message
     * @param  array   $headers
     * @return void
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function abort($code, $message = '', array $headers = array())
    {
        if ($code == 404)
        {
            throw new NotFoundHttpException($message);
        }
    
        throw new HttpException($code, $message, null, $headers);
    }
    

    So it appears that the abort method is simply a helper which throws a NotFoundHttpException if the code 404 is passed, otherwise it throws an HttpException.

    I'm not sure why throwing an Exception would result in logging while using abort() does not. You might want to check your exception handlers and see if different types of exceptions are being caught and handled differently.

    You shouldn't be worrying about the size of your log files. Storage is extremely cheap these days and text takes very little space. The knowledge you gain from your logs will far outweigh their physical cost.