How to return AJAX errors from Laravel Controller?
I am building a REST API with Laravel 5.
In Laravel 5, you can subclassApp\Http\Requests\Requestto define the validation rules that must be satisfied before a particular route will be processed. For example:
<?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, andBookStoreRequestfinds that the request doesn’t satisfy the rules, it will automagically return the error(s) as a JSON object. For example:
{
"title": [
"The title field is required."
]
}
However, theRequest::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:
<?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 justdie(), but that’s super ugly. I would prefer to return my error message in the same format as the validation errors. Like this:
{
"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.
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?
You can set the status code in your json response as below:
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
You can do it in many ways.
First, you can use the simpleresponse()->json()by providing a status code:
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.
OpenApp\Exceptions\Handlerand do the following:
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 createMyCustomException, for example in 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 useMyCustomExceptionor any exception extendingMyCustomExceptionto return a json error.
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 viaMyCustomExceptionwill return a json error, but any other exception thrown in general.
How to return AJAX errors from Laravel Controller?的更多相关文章
- laravel controller重写
<?php namespace Boss\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illumina ...
- How to use external classes and PHP files in Laravel Controller?
By: Povilas Korop Laravel is an MVC framework with its own folder structure, but sometimes we want t ...
- ajax请求提交到controller后总是不成功
最近在做实习时,点击查询时在js中发送ajax请求到controller后台,但是无论怎么样都不成功,请求地址是正确的,因为在后台用system.out.println输出有值,并且也确实return ...
- AJAX json集合传入Controller后台
HTML代码 <html> <head> <meta http-equiv="Content-Type" content="text/htm ...
- 使用JQuery Ajax请求,在Controller里获取Session
昨天在做项目的时候,两个平台之间的切换,虽然两个网站的Session都指向了同一台机子,但是通过Ajax方式来请求时,就是不能获取到Session的值. 在调试的过程中发现,原来是Session的Is ...
- Laravel Controller中引入第三方类库
Laravel 引入第三方类库 在Controller中引入自定义的php文件,先在app目录下创建一个新的文件夹,命名Tools(可自定义),接着创建一个MyTest.php: <?php c ...
- 关于ajax的与后台Controller的交互 后台拿不到值
话不多说 上代码 这是前段js的代码 传的两个参数 cLassid 和 userid $.ajax({ type:"post", url:"../ ...
- angular ajax的使用及controller与service分层
一个简单的例子,控制层:.controller('publishController',['$scope','publishService', function($scope,publishServi ...
- ajax传递参数与controller接收参数映射关系
将ajax的参数传递至后台controller时,data 中的参数名要与controller中的形参保持一致. 前端ajax代码: 1 $.ajax({ 2 url:"/doLogin&q ...
随机推荐
- 解决python3.6的UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 28613: illegal multibyte sequence
这是python3.6的print()函数自身有限制,不能完全打印所有的unicode字符. 主要的是windows下python的默认编码不是'utf-8',改一下python的默认编码成'utf- ...
- Process对象的其他属性:
标签(空格分隔): process join方法: 在主进程运行过程中如果想并发地执行其他的任务,我们可以开启子进程,此时主进程的任务与子进程的任务分两种情况: 情况一:在主进程的任务与子进程的任务彼 ...
- ssh 使用 aws
使用 PuTTY 从 Windows 连接到 Linux 实例 启动您的实例之后,您可以连接到该实例,然后像使用您面前的计算机一样来使用它. 注意 启动实例后,需要几分钟准备好实例,以便您能连接到实例 ...
- metasploit framework(一):基本使用
它位于/usr/share/metasploit-framework 进入到modules目录,有六大模块 exploits:系统漏洞利用的流程,对系统漏洞注入一些特定的代码,使其覆盖程序执行寄存器, ...
- 解题4(NumberToEnglish )
题目描述 Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文: 如22:twenty two,123:one hundred and twenty three. 说明: 数字为正整数, ...
- Forms.WebBrowser与Controls.WebBrowser区别
Forms.WebBrowser与Controls.WebBrowser区别 Forms.WebBrowser有ScrollBarsEnabled 属性,即窗口滚动条,可以设置为false即可: Co ...
- PHP伪原创同义词替代代码示意
PHP伪原创同义词替代代码示意很多网站后台都是支持PHP,虽然用同义词百度能够识别,但至少比原封不动好些,没有AI原创NLP原创度高,但也有一定的效果.下面就是PHP代码实例: <?phpreq ...
- Allowing GPU memory growth
By default, TensorFlow maps nearly all of the GPU memory of all GPUs (subject to CUDA_VISIBLE_DEVICE ...
- 导入Unity插件时出现Failed to import package with error: Couldn't decompress package
导入Unity插件时出现Failed to import package with error: Couldn't decompress package 一开始以为压缩包本身有问题,坏了 后来发现在父 ...
- Bugku——Flag在index里(http://120.24.86.145:8005/post/)
Bugku——Flag在index里(http://120.24.86.145:8005/post/) 进入题目发现有一个file参数,查看源码,发现该参数可以包含php文件,并且题目提示,flag在 ...