api返回实现
1
2
3
4
5
6
7
|
$result = User::find( $id );
if ( empty ( $result )){
throw new ApiException( '获取失败' );
}
else {
return json_decode( $result );
}
|
api返回信息
1
2
3
4
5
|
{
"msg" : "" ,
"data" : "获取失败" ,
"status" : 0
}
|
1,添加异常类
1
2
3
4
5
6
7
8
9
10
11
12
|
namespace App\Exceptions;
class ApiException extends \Exception
{
function _construct( $msg = '' )
{
parent::_construct( $msg );
}
}
|
2,修改laravel异常类u。。。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
namespace App\Exceptions;
public function render( $request , Exception $e )
{
if ( $e instanceof ApiException){
$result = [
"msg" => "" ,
"data" => $e ->getMessage(),
"status" =>0
];
return response()->json( $result );
}
return parent::render( $request , $e );
|
考虑开发配置时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public function render( $request , Exception $e )
{
if (config( 'app.debug' )){
return parent::render( $request , $e );
}
return $this ->handle( $request , $e );
}
public function handle( $request ,Exception $e ){
if ( $e instanceof ApiException){
$result = [
"msg" => "" ,
"data" => $e ->getMessage(),
"status" =>0
];
return response()->json( $result );
}
return parent::render( $request , $e );
}
|
以上这篇laravel框架 api自定义全局异常处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/miss_shy/article/details/79305215