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. 去掉Android新建项目的顶部标题

    [ 去掉Android新建项目的顶部标题] 使用NoActionBar的Theme即可. 参考:http://blog.csdn.net/u012246458/article/details/5299 ...

  2. Java,JDK动态代理的原理分析

    1. 代理基本概念: 以下是代理概念的百度解释:代理(百度百科) 总之一句话:三个元素,数据--->代理对象--->真实对象:复杂一点的可以理解为五个元素:输入数据--->代理对象- ...

  3. mybatis 插入返回自增后的id

    //serviceImpl int customerId = customerDao.insertDynamic(customer1); System.out.println("id==== ...

  4. .net 中使用oracle 的sql 语句

    string sqlString = "Select * From emp  Where EMPNO=7369“; 一定不要写成 string sqlString = "Selec ...

  5. 二:python 对象类型概述

    1,为什么使用内置类型: a)内置对象使程序更容易编写 b)内置对象是扩展的组件 c)内置对象往往比定制的数据结构更加高效 d)内置对象是语言的标准的一部分 2,python  的主要内置对象 对象类 ...

  6. nginx 刷新显示404

    HTML5 History 模式 vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载. 如果不想要很丑的 ...

  7. 第四章 栈与队列(c5)栈应用:逆波兰表达式

  8. 聚合查询、分组查询、F&Q查询

    一.聚合查询和分组查询 1.aggregate(*args, **kwargs): 通过对QuerySet进行计算,返回一个聚合值的字典.aggregate()中每个参数都指定一个包含在字典中的返回值 ...

  9. c语言的基础知识

    break只对应for循环,while循环,switch case分支. (a>b)?y:n    如果A大于B,那么选择Y的结果,如果A小于B,那么选择N的结果. ^在c语言中代表的是按位异或 ...

  10. vue 调用第三方接口配置

    1.配置proxyTable 3.调用接口,将接口地址替换为配置的‘/api’