Return messages through exceptions

Asked

Viewed 331 times

0

Hello, I generated a doubt regarding the most "elegant" way for my method to display a message to the user.

I’m using the following blade in order to return messages, but it does not return Exceptions, in fact exceptions lock my application whenever they are fired.

Note that in my method verificarUpdate there are some scenarios that might be interesting to show how feedback to the user.

Is there any way that in some cases these exceptions will be received for error message? The Standard brings some ease to this?

feedback.blade.php

    @if ($errors->any())
        <div class="alert alert-danger">
                @foreach ($errors->all() as $error)
                    {{ $error }}
                    <br/>
                @endforeach
        </div>
    @endif

    @if (isset($mensagem))
    <div class="alert alert-success">
        {{ $mensagem }}
    </div>
    @endif

Registered Class orderly

namespace App\Services;

use App\Encarregado;
use Illuminate\Support\Facades\DB;
use Exception;

class RegistradorDeEncarregado
{

    public function desabilitarEncarregado(int $id): Encarregado
    {
        DB::beginTransaction();
        $result = Encarregado::where('id', $id)
        ->update([
            'ativo' => 0]);
        DB::commit();

        return $this->verificarUpdate($result, $id);
    }

    private function verificarUpdate(bool $result, $id){
        $encarregado = Encarregado::find($id);

        // Cenário perfeito
        if($result && isset($encarregado)){
            return $encarregado;

        // Quando o id que vai sofrer a alteração já possui 
        // o mesmo valor do parâmetro
        }else if(!$result && isset($encarregado)){
            throw new Exception('Registro já se encontra com o(s) parâmetro(s) de alteração.');

        // Id não existente
        }else{
            throw new Exception('Não foi possível alterar o registro do encarregado.');
        }
    }
}

Encarregadocontroller Class

    public function disability(
            Request $request,
            RegistradorDeEncarregado $registradorDeEncarregado)
    {
        $encarregado = $registradorDeEncarregado->desabilitarEncarregado($request->id);
        $request->session()
            ->flash(
                'mensagem',
                "Encarregado {$encarregado->nome} salvo com sucesso."
            );

        return redirect()->route('encarregado_listar_ativos');
    }
  • I couldn’t understand the more elegant display. Are you saying normal messages from your system from an array['Success','Danger','info','Warning'] OR application errors, fatalError, etc? Edit your question to make it clearer so we can help you better. Hug

  • Edited question. In general, I am trying to bring the exeptions cited in my method to the system screen.

1 answer

1


Exception should not be shown, they may even contain sensitive data that should not be read by ordinary users. But if you want to make them appear in the app is to do:

try {
    ..codigo
} catch (Exception $e) {
    echo 'Exceção capturada: ',  $e->getMessage();
}

As you are using Lade, then in catch you have to return the view as the variable of the Exception message.

Type:

try {
    ..codigo
} catch (Exception $e) {
    $mensagemErro = $e->getMessage();
    return view('paginaView', ['erro' => $mensagemErro]);
}
  • In a way, then, an interesting strategy would be to return a generic message to the user and through some kind of log record the exception generated to be dealt with later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.