Skip to content

Commit

Permalink
异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
leo108 committed Dec 22, 2018
1 parent e6984bb commit 33391dc
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 2 deletions.
2 changes: 1 addition & 1 deletion app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Handler extends ExceptionHandler
* @var array
*/
protected $dontReport = [
//
InvalidRequestException::class,
];

/**
Expand Down
26 changes: 26 additions & 0 deletions app/Exceptions/InternalException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;

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]);
}
}
24 changes: 24 additions & 0 deletions app/Exceptions/InvalidRequestException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;

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]);
}
}
3 changes: 2 additions & 1 deletion app/Http/Controllers/ProductsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\Product;
use Illuminate\Http\Request;

Expand Down Expand Up @@ -54,7 +55,7 @@ public function show(Product $product, Request $request)
{
// 判断商品是否已经上架,如果没有上架则抛出异常。
if (!$product->on_sale) {
throw new \Exception('商品未上架');
throw new InvalidRequestException('商品未上架');
}

return view('products.show', ['product' => $product]);
Expand Down
12 changes: 12 additions & 0 deletions resources/views/pages/error.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
@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

0 comments on commit 33391dc

Please sign in to comment.