简体   繁体   English

Laravel API 错误和异常:如何返回响应

[英]Laravel API Errors and Exceptions: How to Return Responses

Status Code Meaning 404 Not Found (page or other resource doesn't exist) 401 Not authorized (not logged in) 403 Logged in but access to requested area is forbidden 400 Bad request (something wrong with URL or parameters) 422 Unprocessable Entity (validation failed) 500 General server error状态码 含义 404 未找到(页面或其他资源不存在) 401 未授权(未登录) 403 已登录但禁止访问请求的区域 400 错误请求(URL 或参数有问题) 422 无法处理的实体(验证失败)500 一般服务器错误

Not entirely sure what do you want, but you can make your own custom JSON response() with custom status code using JSON responses不完全确定您想要什么,但您可以使用JSON 响应使用自定义状态代码制作自己的自定义JSON response()

return response()->json(['error' => 'Page not found'], 404);

I believe you want something dynamic like 200 for a successful route, 201 for a successful request, 422 for a failed validation and things like that.我相信你想要一些动态的东西,比如 200 表示成功的路线,201 表示成功的请求,422 表示失败的验证等等。 Add this to your controller将此添加到您的 controller

use Symfony\Component\HttpFoundation\Response;

Your delete method should now look like this您的删除方法现在应该如下所示

public function destroy(Job $job)
    {
        //I'm applying model binding
        $job->delete();
        return response([], Response::HTTP_NO_CONTENT);
    }

Your update method should e something like this你的更新方法应该是这样的

public function update(Job $job)
    {
        //I'm using model binding and a resource in my case
        $job->update($this->validateRequest());
        return (new JobResource($job))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

Your store method should be something like this你的 store 方法应该是这样的

public function store(Request $request)
    {
        //I've used a Resource on my Job model
        $job = Job::create($this->validateRequest());

        return (new JobResource($job))
                    ->response()
                    ->setStatusCode(Response::HTTP_CREATED);
    }

This is a sample validate request这是一个示例验证请求

private function validateRequest()
    {
        return request()->validate([
            'title'=> 'required|unique:jobs',
            'comment' => 'sometimes'
        ]);
    }

You can send a response in json format:您可以发送 json 格式的响应:

return response()->json(['error' => 'Page not found'], 404);

If you also want to display a customized message.如果您还想显示自定义消息。 Just add this function from: vendor\laravel\framework\src\Illuminate\Foundation .只需从以下位置添加此 function: vendor\laravel\framework\src\Illuminate\Foundation you do not need to add or require extra files.您不需要添加或需要额外的文件。

abort(403, 'Unauthorized action.');

on any condition you like:在您喜欢的任何条件下:

if ( !hasRole('admin') ) {

                     abort(403, 'Unauthorized action.');
                 }

this is the function:这是 function:

> public function abort($code, $message = '', array $headers = [])
>     {
>         if ($code == 404) {
>             throw new NotFoundHttpException($message);
>         }
> 
>         throw new HttpException($code, $message, null, $headers);
>     }

this is gonna show a general message, if you want to customize your page just add a folder inside resources/view with the name of 'errors', inside add your view with name of errors: 404, 403, etc. The number of error you call in the function, the name of the view laravel will diplay.这将显示一条一般消息,如果您想自定义页面,只需在resources/view中添加一个文件夹,名称为“错误”,在里面添加您的视图,错误名称为:404、403 等。错误数您在 function 中调用,将显示视图名称 laravel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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