laravel返回统一格式错误码问题(2)
但是在laravel中怎么返回这个格式成了一个问题,网上查了好几次,都没有太好的解决办法,多是覆盖的情况不全,再有就是错误码错误信息都写在逻辑层,新加的完全不知道有没有冲突。
后来又在BD和GG搜索好久,自己也尝试用laravel自带的异常机制和Middleware处理,始终不是太满意。
用过JAVA的都知道,在java中处理错误码很方便,直接定义一个枚举把所有的错误代码都写在里面,抛出异常的时候枚举当做参数传递进去。类似于这样
枚举
package *.*.*
public enum ErrorCode {
OK("ok", 0),
PARAM_ERROR("param error", 88888),
UNKNOWN_ERROR("unknown error", 99999);
ErrorCode(String value, Integer key) {
this.value = value;
this.key = key;
}
private String value;
private Integer key;
public String getValue() {
return value;
}
public Integer getKey() {
return key;
}
}
异常类
package *.*.*;
import *.*.*.ErrorCode;
public class ApiException extends Exception {
public int code = 0;
public ApiException(ErrorCode errorCode) {
super(errorCode.getValue());
this.code = errorCode.getKey();
}
......
}
使用
throw new ApiException(ErrorCode.UNKNOWN_ERROR);
于是查了下PHP的枚举,还真支持,但仔细一研究才发现,PHP的枚举不仅要安装开启SPL,然而提供的方法也并没有什么卵用
于是仿照JAVA写了一个
基类
namespace App\Enums;
abstract class Enum
{
public static function __callStatic($name, $arguments)
{
return new static(constant('static::' . $name));
}
}
错误码 这里因为用到了魔术方法,所以要在注视中标注
namespace App\Enums;
/**
* @method static CodeEnum OK
* @method static CodeEnum ERROR
*/
class CodeEnum extends Enum
{
public const OK = ['0', 'ok'];
public const ERROR = ['99999', 'fail'];
private $code;
private $msg;
public function __construct($param)
{
$this->code = reset($param);
$this->msg = end($param);
}
public function getCode()
{
return $this->code;
}
public function getMsg()
{
return $this->msg;
}
}
自定义异常类
namespace App\Exceptions;
use App\Enums\CodeEnum;
use Exception;
use Illuminate\Support\Facades\Log;
class ApiException extends Exception
{
public function __construct(CodeEnum $enum)
{
parent::__construct($enum->getMsg(), $enum->getCode());
}
public function report()
{
Log::error("ApiException {$this->getFile()}({$this->getLine()}): code({$this->getCode()}) msg({$this->getMessage()})");
}
public function render($request)
{
return response([
'code' => $this->getCode(),
'msg' => $this->getMessage(),
'data' => ''
]);
}
}
内容版权声明:除非注明,否则皆为本站原创文章。

