简体   繁体   中英

best way to handle errors in laravel

I am stuck a bit, I have a little form and auth system - Sentry.

1) Get data from Input and validate it. It's okay, I get it, check with rules, set messageBag

<?php
     $validation->getMessageBag()->setFormat(Config::get('project/config.errors_delimiters'));
?>

Then I return page withErrors method. And prints validation errors.

2) Next step will be to login users, for example. This mean, that I need to use a Sentry manual .

But now I have a problem: how to show errors or store errors. I have:

  • Error messages via validation
  • Error messages via Sentry
  • Custom Errors
  • Success messages
  • Info messages

Which the best practice to store this messages? How to send it to a view? And how to parse it in a view? Also how to set delimiters style?

Of course I can create tons of flash, session, and other types of data and then send this into a view, but I think it is ridiculous. I think there is a simple method which can help me.

Very good question. This is how I handle it.

Because validation errors uses MessageBag, what I did is

$messages = new MessageBag;

and then if you run into any error, you could do

try {
    ...
} catch (Exception $e) {
    $messages->add("error", $e->getMessage());
}

and if you have other errors returned you can merge it

$messages->merge($other_messages)

which includes validation messages $validation->messages().

Because messagebag accepts keys, you can add other type by $messages->add('info', 'ok')

And then in your template, or controller, you can get messages of that type by

$messages->get('error')

after you checked with

$messages->has('error')

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