zoukankan      html  css  js  c++  java
  • laravel异常处理

    1.场景:正常PC访问时,如点击商品时,此时商品刚好下架,那么要如何给出相应的提示?

    php artisan make:exception InvalidRequestException

    从5.5版本后,支持在异常类中定义render()方法.异常触发时会自动调用render();

    namespace AppExceptions;
    
    use Exception;
    use IlluminateHttpRequest;
    
    class InvalidRequestException extends Exception
    {
        public function __construct(string $message = "", int $code = 400)
        {
            parent::__construct($message, $code);
        }
    
        public function render(Request $request)
        {
            if ($request->expectsJson()) {
                // json() 方法第二个参数就是 Http 返回码
                return response()->json(['msg' => $this->message], $this->code);
            }
    
            return view('pages.error', ['msg' => $this->message]);
        }
    }

    2.再在view/pages/error.blade.php里做好模板

    @extends('layouts.app')
    @section('title', '错误')
    
    @section('content')
    <div class="card">
        <div class="card-header">错误</div>
        <div class="card-body text-center">
            <h1>{{ $msg }}</h1>
            <a class="btn btn-primary" href="{{ route('root') }}">返回首页</a>
        </div>
    </div>
    @endsection

    3.当出现异常时,laravel默认会写到日志里,那么如何关掉因这个类而产生的日志呢

    app/Exceptions/Handler.php
    
        protected $dontReport = [
            InvalidRequestException::class,
        ];
    

    4.还有一种异常,即要给个信息到用户看,也在存个信息到日志,而这俩错误信息是不同的内容时:

      php artisan make:exception InternalException

    namespace AppExceptions;
    
    use Exception;
    use IlluminateHttpRequest;
    
    class InternalException extends Exception
    {
        protected $msgForUser;
    
        public function __construct(string $message, string $msgForUser = '系统内部错误', int $code = 500)
        {
            parent::__construct($message, $code); //这里会自动存错误到日志
            $this->msgForUser = $msgForUser;
        }
    
        public function render(Request $request)
        {
            if ($request->expectsJson()) {  //这里给上面指定的错误信息给到用户
                return response()->json(['msg' => $this->msgForUser], $this->code);
            }
    
            return view('pages.error', ['msg' => $this->msgForUser]);
        }
    }

     在控制器中就直接这么用

            if (!$product->on_sale) {
                throw new InvalidRequestException('商品未上架');
            }
  • 相关阅读:
    从缓冲上看阻塞与非阻塞socket在发送接收上的区别
    关于TCP封包、粘包、半包
    CURL 和LIBCURL C++代码 上传本地文件,好不容易碰到了这种折腾我几天的代码
    Spring boot 搭配 JPA 生成表注释 和 字段注释
    Spring Data JPA 中常用注解
    SpringBoot Data JPA 关联表查询的方法
    Spring boot data JPA数据库映射关系 : @OneToOne,@OneToMany,@ManyToMany
    Spring Boot Jpa 表名小写转大写
    SpringBoot入门系列~Spring-Data-JPA自动建表
    使用Spring-Session共享使用Session
  • 原文地址:https://www.cnblogs.com/bing2017/p/10848904.html
Copyright © 2011-2022 走看看