碰到需要手动返回错误的情况,可以直接通过laravel中handler类中的render来实现操作即可。render是直接将异常转换为发送回去的浏览器http响应,默认情况下,异常将传递给为你生成响应的基类。不过,你可以按自己意愿检查异常类型或返回自己的自定义响应。
1.执行命令生成一个异常处理类
php artisan make:exception XXXX
生成的文件在app\Exceptions下面
2.对异常类修改
class CommonException extends Exception
{
private $_code = 400;
private $error_data;
//这里的$data是为了trans结合所需的数据来传入的。
public function __construct($cause = 'BusinessException.', $data=[])
{
parent::__construct($cause);
$this->error_data = $data;
}
public function getResponse()
{
//这里的getMessage()是直接拿到 parent::__construct($cause) 传入的$cause参数
$ret = [
'message' => trans('business.' . $this->getMessage(), $this->error_data),
'code' => $this->getMessage(),
'type' => 'business_error',
];
if(!empty($this->error_data)){
$ret['data'] = $this->error_data;
}
//这里直接通过response()->json 这个方法直接返回给前端对应的json数据,第二个参数是对应错误码
return response()->json($ret, $this->_code);
}
}
hanlder类的render方法进行如下修改
public function render($request, Exception $exception)
{
//如果 Content-Type 不是 application/json,呈现框架的错误页面
if ($request->getContentType() && $request->getContentType() != 'json') {
return parent::render($request, $exception);
}
$e = $this->prepareException($exception);
if ($e instanceof CommonException) { //业务错误
return $e->getResponse();
}
}
3.使用方法
try{
if($student['age'] < 18 )
throw new CommonException('The students are under 18');
}catch(CommonException $e){
throw $e;
}
4.前端接收,并提示
this.axios.post(url, {
age : this.age
}).then(response => {
console.log(response)
}).catch(error => {
console.log(error.response)
Notification({
title: '错误提示',
message: error.response.data['message'],
type: "error",
duration: 2000
});
});


这里我们用到了trans本地化翻译
所以我们需要在cn下新建一个business文件
/resources
/lang
/cn
business.php
其中内容为你抛出信息的错误的对应翻译
business.php
<?php
/**
* Copyright (C), 2016-2018, Ghy ins. Co., Ltd.
* File: business.php
* Description: 说明
*
* @author yilu-fyy
* @Create Date 2019/6/25 19:53
* @Update Date 2019/6/25 19:53 By yilu-fyy
* @version v1.0
*/
return [
'The students are under 18' => '学生未满18'
];

本文介绍了如何在Laravel中创建自定义异常处理类,以便在遇到错误时返回格式化的JSON响应,并利用本地化翻译功能提供多语言支持。通过实例演示了如何捕获和处理特定业务异常,并在前端展示相应的错误消息。
1160

被折叠的 条评论
为什么被折叠?



