如何从 Laravel 控制器返回 AJAX 错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35329498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return AJAX errors from a Laravel controller?
提问by greenie2600
I am building a REST API with Laravel 5.
我正在使用 Laravel 5 构建 REST API。
In Laravel 5, you can subclass App\Http\Requests\Request
to define the validation rules that must be satisfied before a particular route will be processed. For example:
在 Laravel 5 中,您可以子类化App\Http\Requests\Request
以定义在处理特定路由之前必须满足的验证规则。例如:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BookStoreRequest extends Request {
public function authorize() {
return true;
}
public function rules() {
return [
'title' => 'required',
'author_id' => 'required'
];
}
}
If a client loads the corresponding route via an AJAX request, and BookStoreRequest
finds that the request doesn't satisfy the rules, it will automagically return the error(s) as a JSON object. For example:
如果客户端通过 AJAX 请求加载相应的路由,并BookStoreRequest
发现请求不满足规则,它将自动将错误作为 JSON 对象返回。例如:
{
"title": [
"The title field is required."
]
}
However, the Request::rules()
method can only validate input—and even if the input is valid, other kinds of errors could arise after the request has already been accepted and handed off to the controller. For example, let's say that the controller needs to write the new book information to a file for some reason—but the file can't be opened:
然而,该Request::rules()
方法只能验证输入——即使输入是有效的,在请求已经被接受并移交给控制器之后,其他类型的错误也可能出现。例如,假设控制器出于某种原因需要将新书信息写入文件 - 但文件无法打开:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\BookCreateRequest;
class BookController extends Controller {
public function store( BookStoreRequest $request ) {
$file = fopen( '/path/to/some/file.txt', 'a' );
// test to make sure we got a good file handle
if ( false === $file ) {
// HOW CAN I RETURN AN ERROR FROM HERE?
}
fwrite( $file, 'book info goes here' );
fclose( $file );
// inform the browser of success
return response()->json( true );
}
}
Obviously, I could just die()
, but that's super ugly. I would prefer to return my error message in the same format as the validation errors. Like this:
显然,我可以die()
,但那太丑了。我更愿意以与验证错误相同的格式返回我的错误消息。像这样:
{
"myErrorKey": [
"A filesystem error occurred on the server. Please contact your administrator."
]
}
I could construct my own JSON object and return that—but surely Laravel supports this natively.
我可以构建我自己的 JSON 对象并返回它——但肯定 Laravel 本身就支持这一点。
What's the best / cleanest way to do this? Or is there a better way to return runtime (as opposed to validate-time) errors from a Laravel REST API?
什么是最好/最干净的方法来做到这一点?或者有没有更好的方法从 Laravel REST API 返回运行时(而不是验证时间)错误?
回答by Jilson Thomas
You can set the status code in your json response as below:
您可以在 json 响应中设置状态代码,如下所示:
return Response::json(['error' => 'Error msg'], 404); // Status code here
Or just by using the helper function:
或者只是使用辅助函数:
return response()->json(['error' => 'Error msg'], 404); // Status code here
回答by Blue Genie
You can do it in many ways.
您可以通过多种方式做到这一点。
First, you can use the simple response()->json()
by providing a status code:
首先,您可以response()->json()
通过提供状态代码来使用 simple :
return response()->json( /** response **/, 401 );
Or, in a more complexe way to ensure that every error is a json response, you can set up an exception handler to catch a special exception and return json.
或者,以更复杂的方式确保每个错误都是 json 响应,您可以设置异常处理程序来捕获特殊异常并返回 json。
Open App\Exceptions\Handler
and do the following:
打开App\Exceptions\Handler
并执行以下操作:
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
NotFoundHttpException::class,
// Don't report MyCustomException, it's only for returning son errors.
MyCustomException::class
];
public function render($request, Exception $e)
{
// This is a generic response. You can the check the logs for the exceptions
$code = 500;
$data = [
"error" => "We couldn't hadle this request. Please contact support."
];
if($e instanceof MyCustomException) {
$code = $e->getStatusCode();
$data = $e->getData();
}
return response()->json($data, $code);
}
}
This will return a json for any exception thrown in the application.
Now, we create MyCustomException
, for example in app/Exceptions:
这将为应用程序中抛出的任何异常返回一个 json。现在,我们创建MyCustomException
,例如在 app/Exceptions 中:
class MyCustomException extends Exception {
protected $data;
protected $code;
public static function error($data, $code = 500)
{
$e = new self;
$e->setData($data);
$e->setStatusCode($code);
throw $e;
}
public function setStatusCode($code)
{
$this->code = $code;
}
public function setData($data)
{
$this->data = $data;
}
public function getStatusCode()
{
return $this->code;
}
public function getData()
{
return $this->data;
}
}
We can now just use MyCustomException
or any exception extending MyCustomException
to return a json error.
我们现在可以只使用MyCustomException
或 任何扩展MyCustomException
来返回 json 错误的异常。
public function store( BookStoreRequest $request ) {
$file = fopen( '/path/to/some/file.txt', 'a' );
// test to make sure we got a good file handle
if ( false === $file ) {
MyCustomException::error(['error' => 'could not open the file, check permissions.'], 403);
}
fwrite( $file, 'book info goes here' );
fclose( $file );
// inform the browser of success
return response()->json( true );
}
Now, not only exceptions thrown via MyCustomException
will return a json error, but any other exception thrown in general.
现在,不仅通过抛出的异常MyCustomException
将返回一个 json 错误,而且任何其他一般抛出的异常。