简体   繁体   中英

How to add custom error in Laravel?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM