Laravel 5: Custom abort() message

2020-06-08 23:37发布

问题:

Using Laravel 5, I want to send a custom abort() message.
For example, if the user doesn't have the required permissions for an action,
I'd like to abort(401, "User can't perform this actions").
Currently, when I do so, the response text is HTML page and not the message.
How can I return only the message?

Note: I don't want to pass a different view, but only the custom message.

回答1:

According to Laravel 5.4 documentation:

https://laravel.com/docs/5.4/errors#http-exceptions

You can use abort helper with response text:

abort(500, 'Something went wrong');

And use $exception->getMessage() in resources/views/errors/500.blade.php to display it:

Error message: {{ $exception->getMessage() }}


回答2:

The answer is simply to use the response() helper method instead of abort(). Syntax as below.

return response("User can't perform this action.", 401);


回答3:

You can wrap a response inside abort, which will stop the execution and return the response. If you want it to be JSON then add ->json();

# Regular response
abort( response('Unauthorized', 401) );

# JSON response 
abort( response()->json('Unauthorized', 401) );


回答4:

You can handle all error exceptions here app/Exceptions/Handler.php Class On your requirement.

In your case just replace render function with this

public function render($request, Exception $e)
{
   return $e->getMessage();
   //For Json
   //return response()->json(['message' => $e->getMessage()]);
}


回答5:

Should be able to use the following in the template:

{{ $exception->getMessage() }}


回答6:

First of all add the error message in your header file or in the page where you want to show the message like:

@if($errors->has())
    @foreach ($errors->all() as $error)
        <div>{{ $error }}</div>
    @endforeach
@endif

And in the controller, you can do this kind of stuff (e.g.):

public function store(){
    if(user is not permitted to access this action) // check user permission here
    {
        return redirect()->back()->withErrors("User can't perform this actions");
    }
}

You can redirect back with error message



回答7:

In Handler.php I altered the function:

 public function render($request, Exception $e)
{
    $response = parent::render($request, $e);

    if (method_exists($e, "getStatusCode")) {
        if ($e->getStatusCode() == 401) {
            $response->setContent($e->getMessage());
        }
    }

    return $response;
}