Questions:

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?

Answers:

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
Answers:

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?的更多相关文章

  1. laravel controller重写

    <?php namespace Boss\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illumina ...

  2. 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 ...

  3. ajax请求提交到controller后总是不成功

    最近在做实习时,点击查询时在js中发送ajax请求到controller后台,但是无论怎么样都不成功,请求地址是正确的,因为在后台用system.out.println输出有值,并且也确实return ...

  4. AJAX json集合传入Controller后台

    HTML代码 <html> <head> <meta http-equiv="Content-Type" content="text/htm ...

  5. 使用JQuery Ajax请求,在Controller里获取Session

    昨天在做项目的时候,两个平台之间的切换,虽然两个网站的Session都指向了同一台机子,但是通过Ajax方式来请求时,就是不能获取到Session的值. 在调试的过程中发现,原来是Session的Is ...

  6. Laravel Controller中引入第三方类库

    Laravel 引入第三方类库 在Controller中引入自定义的php文件,先在app目录下创建一个新的文件夹,命名Tools(可自定义),接着创建一个MyTest.php: <?php c ...

  7. 关于ajax的与后台Controller的交互 后台拿不到值

    话不多说 上代码 这是前段js的代码        传的两个参数    cLassid  和  userid $.ajax({ type:"post", url:"../ ...

  8. angular ajax的使用及controller与service分层

    一个简单的例子,控制层:.controller('publishController',['$scope','publishService', function($scope,publishServi ...

  9. ajax传递参数与controller接收参数映射关系

    将ajax的参数传递至后台controller时,data 中的参数名要与controller中的形参保持一致. 前端ajax代码: 1 $.ajax({ 2 url:"/doLogin&q ...

随机推荐

  1. java搭建web从0-1(第一步:创建web工程)

    intellij idea版本:2017 1.新建一个web工程 使用工具intellij ideal,注意:只有Ultimate版本的可以新建web工程,社区版本的不支持新建web工程   File ...

  2. BeautifulSoup中查找元素 select() 和find()区别

    从html中查找元素,之前一般都用find(),查找符合条件的第一个,如下 f = open(file, 'r') # 读取文件内容content = f.read()soup= BeautifulS ...

  3. jquery+jquery.pagination+php+ajax 无刷新分页

    <!DOCTYPE html> <html ><head><meta http-equiv="Content-Type" content= ...

  4. GIT 命令集

    Git图形化界面 下面是我整理的常用 Git 命令清单.几个专用名词的译名如下. Workspace:工作区 Index / Stage:暂存区 Repository:仓库区(或本地仓库) Remot ...

  5. 最小生成树算法(krustra+prime)

    给你一个图,求让图连通的边权和最小值 krustra算法是基于加边法,将所有边权排序,每次加一条边,将两个点放在同一个集合中.如果新加的点不在同一个集合中,就合并(并查集) 涉及到排序,可以用结构体存 ...

  6. FZU-1752.(A^B mod C)(快速幂与快速乘优化)

    我把自己演哭了... 心酸.jpg 写了很多个版本的,包括数学公式暴力,快速幂TLE等等,最后想到了优化快速幂里的乘法,因为会爆longlong,但是和别人优化的效率简直是千差万别...? 本题大意: ...

  7. Java之成员访问控制

    Java中数据成员.方法成员有四种访问控制.

  8. 微信小程序开发——小程序API获取用户位置及异常流处理完整示例

    前言: 小程序需要添加一个定位功能,主要的就是获取用户位置的经纬度,然后根据用户经纬度进行一些判断操作. 在小程序提供的Api中,获取用户定位信息的主要Api是 wx.getLocation(obj) ...

  9. javascript根据身份证号判断精确周岁年龄

    前言: 根据身份证号判断精确周岁年龄,可以精确到天,即周岁以生日当天为准,生日当天周岁+1,少一天则不加. 实现方法: <!DOCTYPE html> <html> <h ...

  10. [Java学习]面向对象-多态

    多态 多态发生条件 发生在有继承关系的类型中. 向上转型(自动类型转换)与向下转型(强制类型转换) //向上转型 //编译阶段a1被编译器看作是Animal类型,所以a1引用绑定的是Animal类中的 ...