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\Request
to 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, andBookStoreRequest
finds 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\Handler
and 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 useMyCustomException
or any exception extendingMyCustomException
to 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 viaMyCustomException
will 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 ...
随机推荐
- 2017面向对象程序设计(Java) 第1周学习指导及要求(2017.8.24-2017.8.27)
2017面向对象程序设计(Java) 第1周学习指导及要求(2017.8.24-2017.8.27) 学习目标 了解课程上课方式及老师教学要求,掌握课程学习必要的软件工具: 简单了解Java特点及 ...
- 《java与模式》阅读笔记01
这次我读了前两章的内容,就如书名所言,这本书主要将的就是java中的模式,在书中的序言就把所有的模式都介绍了一下,主要有, 1.创建模式:简单工厂模式,工厂方法模式,抽象工厂模式,建造模式 2.行为模 ...
- vue bus 的使用
简单的状态管理,可以用vue bus vue bus可以实现不同组件间.不同页面间的通信,比如我在A页面出发点击事件,要B页面发生变化,使用方法如下: 全局定义:main.js window.even ...
- openstack(Pike 版)集群部署(七)--- Cinder 部署
一.介绍 参照官网部署:https://docs.openstack.org/cinder/pike/install/index-rdo.html 继续上一博客进行部署:http://www.cnbl ...
- Aladdin and the Flying Carpet
Aladdin and the Flying Carpet https://cn.vjudge.net/contest/288520#problem/C It's said that Aladdin ...
- ACM-ICPC 2018 南京赛区网络预赛 G. Lpl and Energy-saving Lamps(二分+线段树区间最小)
During tea-drinking, princess, amongst other things, asked why has such a good-natured and cute Drag ...
- 写一写关于python开发面试的常遇到的问题以及解答吧,持续更新——看心情
1,什么是python中的魔术方法? 魔术方法是重载运算符的昵称,形式是__init__类似这样的前后双下滑线组成的,常用的__init__,__new__,__call__,__str__,__ge ...
- 在别家网站上执行自己的js代码(谷歌浏览器)(谷歌扩展程序)
@参考文章1 @参考文章2 日前针对一家投标网站进行了程序干预,且一定程度的干预成功,把方法给大家提取分享出来,感谢上述两篇博文 测试网站:百度https://www.baidu.com/ 测试步骤 ...
- maven 转化gradle
- Java基本语法之动手动脑
1.枚举类型 运行EnumTest.java 运行结果:false,false,true,SMALL,MEDIUM,LARGE 结论:枚举类型是引用类型,枚举不属于原始数据类型,它的每个具体值都引用一 ...