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 ...
随机推荐
- 引用yml中自定义数据 静态引用和动态引用
//静态 @Component public class LinusFile { public static String imageUrl; @Value("${web.uploadPat ...
- BOM进IN_BOM_HEADER表后被过滤掉
1.查看如下两个表发现BOM被过滤掉了 SELECT PRODUCT_ID||'_'||substr(BOM_ID,1,8),A.* FROM IN_BOM_HEADER A WHERE A.PRO ...
- Linq to sql 之 ExecuteQuery 错误:指定的转换无效
问题:通过dbContext.ExecuteQuery 得到数据并赋值给一个集合. 代码: public IEnumerable<LeaveCodeSum> GetLeavTotal(st ...
- cxf怎样提高webservice性能,及访问速度调优
性能: 1. 启用FastInfoset(快速信息集)webservice的性能实在是不敢恭维.曾经因为webservice吞吐量上不去,对webservice进行了一些性能方面的优化,采用了Fast ...
- day18 logging模块 sys shelve
昨日回顾 re 正则表达式 匹配字符串 场景 例如:爬虫,密码规则验证,邮箱地址验证,手机号码 学习re主要学习的就是 那一堆特殊符号 hashlib hash是一种算法 lib表示库 该模块包含了一 ...
- c++ 面试题(汇总)
1,extern 关键字作用: http://www.cnblogs.com/lzjsky/archive/2010/11/24/1886686.html 2,static 关键字作用: https: ...
- python 进行机器学习
summary: 本文总结了几种常见的线性回归的的方式以及各种方式的优缺点. 1,简单现性回归(OSL): OSL:就是一种最为简单的普通最小二乘法的实现,y = a0 + a1*x1 + a2*x2 ...
- Centos 7 下 Corosync + Pacemaker + psc + HA-proxy 实现业务高可用
一.介绍: 1.本博客Corosync + Pacemaker + psc + HA-proxy 实现业务高可用,以httpd 服务实现高可用为例. 2.架构思路 a.三台web 节点,功能:全部安装 ...
- python中matplotlib所绘制的图包含了很多的对象
上图中的top=‘off’意思是说顶部的grid lines 看不见. 去除frame,意思就是将这个矩形给去除掉,spine意思是脊柱 bars = plt.bar(pos, popularity, ...
- rdlc报表的导出及预览时表头
感谢各路大神的博客,总结rdlc报表中目前用到的知识,积累. 一.rdlc报表PDF打印出现空白页 1.先至Report.rdlc報表設計的頁面,選擇功能表上的[報表]->[報表屬性],在[配置 ...