laravel11:发生异常时返回json

一,未配置前laravel11直接render页面

如图:

二,配置

1,  bootstrap/app.php

<?php

use Illuminate\Http\Request;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpFoundation\Response;

use App\extend\result\Result;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        
        $exceptions->respond(function (Response $response, Throwable $exception) {
            $msg = $exception->getMessage().' '.$exception->getFile().' '.$exception->getLine();
            return response()->json(['code'=>500,'msg'=>$msg]);
        });


    })->create();

2,触发异常,做一个除0操作

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\extend\result\Result;

class VirtualController extends Controller
{
    //使用统一返回的数据格式
    public function res(Request $request) {

        //判断是否存在name参数,如果存在
        if ($request->has('name')) {
            $data = [
                'name'=>$request->name,
                'age'=>'24',
            ];

            return Result::Success($data);
        } else {   //参数不存在时返回错误

            $z = 0;
            $a = 10 / $z;
            var_dump($a);

            return Result::ErrorCode(10024,'缺少name参数');
        }
    }
}

三,测试效果:

 

posted @ 2024-07-17 10:48  刘宏缔的架构森林  阅读(110)  评论(0编辑  收藏  举报