Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Friday, June 16, 2017

How to Handle Laravel 5.X Exceptions

In Laravel 5.2, all errors and exceptions, both custom and default, are handled by the Handler class in app/Exceptions/Handler.php with the help of two methods ##report & ##render.

The ##report method enables you to log raised exceptions or parse them to error logging engines. 

The ##render method return with an error message as well as response code raised by any exception. It generates a HTTP response from the exception and sends it back to the browser.

We can also override the default behavior of error handling with our own custom exception handler if we need.


/**
 * 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)
{
    //$request->ajax() [[AJAX REQUEST CHECK]]
    if ($e instanceof MyException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.custom', [], 500);
    }
    if ($this->isHttpException($e)) {
        switch ($e->getStatusCode()) {
            case 404:
                return response()->view('errors.404', [], 500);
            case 500:
                return response()->view('errors.500', [], 500);
            default:
                return $this->renderHttpException($e);
        }
    } elseif ($e instanceof TokenMismatchException) {
        return redirect()->back()->withInput()->with('error', 'Your session has expired');
    } else {
        return response()->view('errors.500', [], 500);
    }
}

And finally you have to add a 404.blade.php && 500.blade.php file in resources/view/errors to represent our custom error page.


We can also generate a 404 as well as 500 error page response by calling the abort method which takes an optional response message.

abort(404, 'The resource you are looking for could not be found');


This will check for a related resources/view/errors/404.blade.php and serve a HTTP response with the 404 status code back to the browser. The same applies for 401 and 500 or for other error status codes.








Saturday, February 11, 2017

Laravel throw/return custom exception/response

In Laravel it is very simple to handle exception and return custom error codes to view. Below is a example how you can return custom http header code.


<?php
namespace App\Http\Controllers;

use Request;

class TestController extends Controller { 
   public function test_function(Request $request) {
       return response("content", 430)->header('Content-Type', "text/html");
   }
}
?>

Monday, January 18, 2016

Convert Exception Details To String Using Java

package com.pritom.kumar;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by pritom on 18/01/2016.
 */
public class ExceptionToString {
    public static String convertExceptionToString(Throwable throwable) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            return sw.toString();
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

Friday, September 20, 2013

HTTP Status Codes Handling and Htaccess ErrorDocuments

Error handling using .htacces:

Here are some basic rule, use other rules if you need.

ErrorDocument 404 /Subtitle/php/error-msg.php
ErrorDocument 500 /location/php/error-msg.php
ErrorDocument 400 /location/php/error-msg.php
ErrorDocument 401 /location/php/error-msg.php
ErrorDocument 403 /location/php/error-msg.php

And the error-msg.php like this:

Here are some basic rule, use other rules if you need.

<?php
$HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {
      echo "Document has been processed and sent to you.";      
  } else if($HttpStatus==400) {
      echo "Bad HTTP request ";      
  } else if($HttpStatus==401) {
      echo "Unauthorized - Iinvalid password";      
  } else if($HttpStatus==403) {
      echo "Forbidden";      
  } else if($HttpStatus==500) {
      echo "Internal Server Error";      
  } else if($HttpStatus==418) {
      echo "I'm a teapot! - This is a real value, defined in 1998";      
  } else if($HttpStatus==404) {
      echo "Page not found here";      
  } else {
      $HttpStatus = 500;
      echo "Internal server Error";
  }
  echo "<BR>Status: ".$HttpStatus;
  exit; 
?>

Error Distribute from php file (named: mac_address.php)

If you need to show error like above one, please see below example php code:

<?php
/* UnCaught error handler */
set_exception_handler('exc_handler');

/* Error handler function */
function exc_handler(Exception $exception) {
    /* Set http status code such 404, 500 etc. */
    header("HTTP/1.1 ".$exception->getCode()." ".$exception->getMessage());
    /**
     * As 'REDIRECT_STATUS' is using in 'error-msg.php' file,
     * so we are providing this manually.
     * But it will automatically set when come from .htaccess
     */
    $_SERVER["REDIRECT_STATUS"] = $exception->getCode();
    /**
     * Including 'error-msg.php' file.
     */
    include './error-msg.php';
}
/**
 * Extentd 'Exception' to my own class 'NotFoundException'
 */
class NotFoundException extends Exception {
    public function NotFoundException($message = "Page not found") {
        throw new Exception($message, 404);
    }
}
/**
 * Throwing 'NotFoundException'
 */
//throw new NotFoundException();

/**
 * Another way to throw exception as bellow, where 
 * 'Server error' is the message and
 * '500' is the error code.
 */
throw new Exception("Server error", 500);
?>

Example output in browser (Custom 500 error using php code):

I wrote the code in mac_address.php to show 500 internal server error.














Example output in browser (404 error using .htaccess):

No file in that location named 'mac.php', .htaccess handling this internally.

Monday, September 16, 2013

Grails Controller allow Declarative Exception Handling with Filters

I guess you can handle declarative exception from Controllers but Filters. You can use response instead to send the error code
class AuthorizationFilters {
    def filters = {
        auth(controller: '*' /* or controller name */
            action: '*' /* or action name */, invert: true) {
            before = {
                HashMap map = new HashMap();
                map.put("success", false);
                map.put("message", "Error occurred"); 
                if(1){ //If auth fails
                    response.sendError(5000) /* Custom error code */
                    response.errorMessage = "Error message to error controller";
 
                    // OR 
                    //render(status: 403);
                    //render(contentType: "text/json", text: map.toJSON());
 
                    // OR 
                    //redirect(controller: 'error', action: 'errorDisplay');
                }
                return false
            }
        }
    }
}
Above logic will render the response from ErrorController's errorDisplay action based on the UrlMapping that is provided below.
Make sure you are excluding error controller from filters.

Make sure you have the entry in UrlMappings.groovy:
"5000"(controller: "error", action: "errorDisplay")

And ErrorController.groovy:
class ErrorController {
    def errorDisplay() {
        render(status: 500); /* Change error code to 500 from custom code: 5000 */
        render("Error: "+response.errorMessage);
        //response.errorMessage would be "Error message to error controller";
        return;
    }
}