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. Ubuntu下面的docker开启ssh服务

    选择主流的openssh-server作为服务端: root@161f67ccad50:/# apt-get install openssh-server -y Reading package lis ...

  2. spring boot springmvc视图

    pring boot 在springmvc的视图解析器方面就默认集成了ContentNegotiatingViewResolver和BeanNameViewResolver,在视图引擎上就已经集成自动 ...

  3. cdnbest补充api

    1.应用防火墙---防CC 添加|修改 请求地址: {api_dir}/firewall/anticc 请求方式: PUT 请求参数: frcquency string 触发频率 例:low(低) | ...

  4. Python 函数内变量的作用域

    Python程序中创建.改变.查找变量名时,都是在一个保存变量名的空间中进行,我们称之为命名空间,也被称之为作用域. 全局作用域(global):即在模块层次中定义的变量,每一个模块都是一个全局作用域 ...

  5. linux命令清除服务器缓存

    linux 服务器开了某项服务或程序后,内存占用的非常大,停止服务或关闭进程后,内存不会立即释放,需要手动释放,使用命令 echo 3 > /proc/sys/vm/drop_chaches 释 ...

  6. c/c++ 中的重要函数

    1,strtod: 函数原型: #include <cstdlib> double strtod(const char *nptr, char **endptr); strtod 原型 名 ...

  7. 第三章 列表(a)接口与实现

  8. mysql 取得各种时间

    转载 取得当前日期:DATE_FORMAT(NOW(),'%e'): 取得当前年月:DATE_FORMAT(NOW(),'%Y-%c'):Y:四位.y:两位:m:两位.c:前面不加0: /*当前时间加 ...

  9. java深拷贝与浅拷贝

    1.调用Object类的clone方法必须实现Cloneable接口,clone属于浅拷贝. 2.可以通过java的反序列化机制进行深拷贝. 3.可以直接用apache提供的一些包进行深拷贝和浅拷贝, ...

  10. Hashed collections哈希集合

    [定义] 有index的集合 [hash的原理] term for a situation when two different objects return the same hashcode: h ...