首页 » PHP教程 » php清除trycatch技巧_技能总监手把手教我若何消除项目中丑陋的Try Catch获益匪浅

php清除trycatch技巧_技能总监手把手教我若何消除项目中丑陋的Try Catch获益匪浅

访客 2024-11-08 0

扫一扫用手机浏览

文章目录 [+]

丑陋的 try catch 代码块

丑陋的 try catch 代码块

php清除trycatch技巧_技能总监手把手教我若何消除项目中丑陋的Try Catch获益匪浅

优雅的Controller

php清除trycatch技巧_技能总监手把手教我若何消除项目中丑陋的Try Catch获益匪浅
(图片来自网络侵删)

上面的示例,还只是在Controller层,如果是在Service层,可能会有更多的try catch代码块。
这将会严重影响代码的可读性、“都雅性”。

以是如果是我的话,我肯定倾向于第二种,我可以把更多的精力放在业务代码的开拓,同时期码也会变得更加简洁。

既然业务代码不显式地对非常进行捕获、处理,而非常肯定还是处理的,不然系统岂不是动不动就崩溃了,以是必须得有其他地方捕获并处理这些非常。
公众号(Java后端)还发布过很多编程技巧文章,关注「Java后端」回答 666 下载。

那么问题来了,如何优雅的处理各种非常?

什么是统一非常处理

Spring在3.2版本增加了一个表明@ControllerAdvice,可以与@ExceptionHandler、@InitBinder、@ModelAttribute 等表明表明配套利用,对付这几个表明的浸染,这里不做过多赘述,若有不理解的,可以参考Spring3.2新表明@ControllerAdvice,先大概有个理解。

不过跟非常处理干系的只有表明@ExceptionHandler,从字面上看,便是 非常处理器 的意思,其实际浸染也是:若在某个Controller类定义一个非常处理方法,并在方法上添加该表明,那么当涌现指定的非常时,会实行该处理非常的方法,其可以利用springmvc供应的数据绑定,比如注入HttpServletRequest等,还可以接管一个当前抛出的Throwable工具。

但是,这样一来,就必须在每一个Controller类都定义一套这样的非常处理方法,由于非常可以是各种各样。
这样一来,就会造成大量的冗余代码,而且若须要新增一种非常的处理逻辑,就必须修正所有Controller类了,很不优雅。

当然你可能会说,那就定义个类似BaseController的基类,这样总行了吧。

这种做法虽然没错,但仍不尽善尽美,由于这样的代码有一定的侵入性和耦合性。
简大略单的Controller,我为啥非得继续这样一个类呢,万一已经继续其他基类了呢。
大家都知道Java只能继续一个类。

那有没有一种方案,既不须要跟Controller耦合,也可以将定义的 非常处理器 运用到所有掌握器呢?以是表明@ControllerAdvice涌现了,大略的说,该表明可以把非常处理器运用到所有掌握器,而不是单个掌握器。
借助该表明,我们可以实现:在独立的某个地方,比如单独一个类,定义一套对各种非常的处理机制,然后在类的署名加上表明@ControllerAdvice,统一对 不同阶段的、不同非常 进行处理。
这便是统一非常处理的事理。

把稳到上面对非常按阶段进行分类,大体可以分成:进入Controller前的非常 和 Service层非常,详细可以参考下图:

不同阶段的非常

目标

消灭95%以上的 try catch 代码块,以优雅的 Assert(断言) 办法来校验业务的非常情形,只关注业务逻辑,而不用花费大量精力写冗余的 try catch 代码块。

统一非常处理实战

在定义统一非常处理类之前,先来先容一下如何优雅的剖断非常情形并抛非常。

用 Assert(断言) 更换 throw exception

想必 Assert(断言) 大家都很熟习,比如 Spring 家族的 org.springframework.util.Assert,在我们写测试用例的时候常常会用到,利用断言能让我们编码的时候有一种非一样平常丝滑的觉得,比如:

@Test public void test1() { ... User user = userDao.selectById(userId); Assert.notNull(user, "用户不存在."); ... } @Test public void test2() { // 另一种写法 User user = userDao.selectById(userId); if (user == null) { throw new IllegalArgumentException("用户不存在."); } }复制代码

有没有觉得第一种剖断非空的写法很优雅,第二种写法则是相对丑陋的 if {...} 代码块。
那么神奇的 Assert.notNull() 背后到底做了什么呢?下面是 Assert 的部分源码:

public abstract class Assert { public Assert() { } public static void notNull(@Nullable Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } }}复制代码

可以看到,Assert 实在便是帮我们把 if {...} 封装了一下,是不是很神奇。
虽然很大略,但不可否认的是编码体验至少提升了一个档次。
那么我们能不能模拟org.springframework.util.Assert,也写一个断言类,不过断言失落败后抛出的非常不是IllegalArgumentException 这些内置非常,而是我们自己定义的非常。
下面让我们来考试测验一下。

Assertpublic interface Assert { / 创建非常 @param args @return / BaseException newException(Object... args); / 创建非常 @param t @param args @return / BaseException newException(Throwable t, Object... args); / <p>断言工具<code>obj</code>非空。
如果工具<code>obj</code>为空,则抛出非常 @param obj 待判断工具 / default void assertNotNull(Object obj) { if (obj == null) { throw newException(obj); } } / <p>断言工具<code>obj</code>非空。
如果工具<code>obj</code>为空,则抛出非常 <p>非常信息<code>message</code>支持通报参数办法,避免在判断之提高行字符串拼接操作 @param obj 待判断工具 @param args message占位符对应的参数列表 / default void assertNotNull(Object obj, Object... args) { if (obj == null) { throw newException(args); } }}复制代码

上面的Assert断言方法是利用接口的默认方法定义的,然后有没有创造当断言失落败后,抛出的非常不是详细的某个非常,而是交由2个newException接口方法供应。
由于业务逻辑中涌现的非常基本都是对应特定的场景,比如根据用户id获取用户信息,查询结果为null,此时抛出的非常可能为UserNotFoundException,并且有特定的非常码(比如7001)和非常信息“用户不存在”。
以是详细抛出什么非常,有Assert的实现类决定。
(此处推举一下前日的文章 去掉烦人的 !=null)

看到这里,您可能会有这样的疑问,按照上面的说法,那岂不是有多少非常情形,就得有定义等量的断言类和非常类,这显然是反人类的,这也没想象中高明嘛。
别急,且听我细细道来。

善解人意的Enum

自定义非常BaseException有2个属性,即code、message,这样一对属性,有没有想到什么类一样平常也会定义这2个属性?没错,便是列举类。
且看我如何将 Enum 和 Assert 结合起来,相信我一定会让你面前一亮。
如下:

public interface IResponseEnum { int getCode(); String getMessage();}/ <p>业务非常</p> <p>业务处理时,涌现非常,可以抛出该非常</p> /public class BusinessException extends BaseException { private static final long serialVersionUID = 1L; public BusinessException(IResponseEnum responseEnum, Object[] args, String message) { super(responseEnum, args, message); } public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) { super(responseEnum, args, message, cause); }}public interface BusinessExceptionAssert extends IResponseEnum, Assert { @Override default BaseException newException(Object... args) { String msg = MessageFormat.format(this.getMessage(), args); return new BusinessException(this, args, msg); } @Override default BaseException newException(Throwable t, Object... args) { String msg = MessageFormat.format(this.getMessage(), args); return new BusinessException(this, args, msg, t); }}@Getter@AllArgsConstructorpublic enum ResponseEnum implements BusinessExceptionAssert { / Bad licence type / BAD_LICENCE_TYPE(7001, "Bad licence type."), / Licence not found / LICENCE_NOT_FOUND(7002, "Licence not found.") ; / 返回码 / private int code; / 返回 / private String message;}复制代码

看到这里,有没有面前一亮的觉得,代码示例中定义了两个列举实例:BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,分别对应了BadLicenceTypeException、LicenceNotFoundException两种非常。
往后每增加一种非常情形,只需增加一个列举实例即可,再也不用每一种非常都定义一个非常类了。
然后再来看下如何利用,假设LicenceService有校验Licence是否存在的方法,如下:

/ 校验{@link Licence}存在 @param licence / private void checkNotNull(Licence licence) { ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence); }复制代码

若不该用断言,代码可能如下:

private void checkNotNull(Licence licence) { if (licence == null) { throw new LicenceNotFoundException(); // 或者这样 throw new BusinessException(7001, "Bad licence type."); } }复制代码

利用列举类结合(继续)Assert,只需根据特定的非常情形定义不同的列举实例,如上面的BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,就能够针对不同情形抛出特定的非常(这里指携带特定的非常码和非常),这样既不用定义大量的非常类,同时还具备了断言的良好可读性,当然这种方案的好处远不止这些,请连续阅读后文,逐步体会。

注:上面举的例子是针对特定的业务,而有部分非常情形是通用的,比如:做事器繁忙、网络非常、做事器非常、参数校验非常、404等,以是有CommonResponseEnum、ArgumentResponseEnum、ServletResponseEnum,个中 ServletResponseEnum 会在后文详细解释。

定义统一非常处理器类

@Slf4j@Component@ControllerAdvice@ConditionalOnWebApplication@ConditionalOnMissingBean(UnifiedExceptionHandler.class)public class UnifiedExceptionHandler { / 生产环境 / private final static String ENV_PROD = "prod"; @Autowired private UnifiedMessageSource unifiedMessageSource; / 当前环境 / @Value("${spring.profiles.active}") private String profile; / 获取国际化 @param e 非常 @return / public String getMessage(BaseException e) { String code = "response." + e.getResponseEnum().toString(); String message = unifiedMessageSource.getMessage(code, e.getArgs()); if (message == null || message.isEmpty()) { return e.getMessage(); } return message; } / 业务非常 @param e 非常 @return 非常结果 / @ExceptionHandler(value = BusinessException.class) @ResponseBody public ErrorResponse handleBusinessException(BaseException e) { log.error(e.getMessage(), e); return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e)); } / 自定义非常 @param e 非常 @return 非常结果 / @ExceptionHandler(value = BaseException.class) @ResponseBody public ErrorResponse handleBaseException(BaseException e) { log.error(e.getMessage(), e); return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e)); } / Controller上一层干系非常 @param e 非常 @return 非常结果 / @ExceptionHandler({ NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class, MissingPathVariableException.class, MissingServletRequestParameterException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, HttpMessageNotWritableException.class, // BindException.class, // MethodArgumentNotValidException.class HttpMediaTypeNotAcceptableException.class, ServletRequestBindingException.class, ConversionNotSupportedException.class, MissingServletRequestPartException.class, AsyncRequestTimeoutException.class }) @ResponseBody public ErrorResponse handleServletException(Exception e) { log.error(e.getMessage(), e); int code = CommonResponseEnum.SERVER_ERROR.getCode(); try { ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName()); code = servletExceptionEnum.getCode(); } catch (IllegalArgumentException e1) { log.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName()); } if (ENV_PROD.equals(profile)) { // 当为生产环境, 不适宜把详细的非常信息展示给用户, 比如404. code = CommonResponseEnum.SERVER_ERROR.getCode(); BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR); String message = getMessage(baseException); return new ErrorResponse(code, message); } return new ErrorResponse(code, e.getMessage()); } / 参数绑定非常 @param e 非常 @return 非常结果 / @ExceptionHandler(value = BindException.class) @ResponseBody public ErrorResponse handleBindException(BindException e) { log.error("参数绑定校验非常", e); return wrapperBindingResult(e.getBindingResult()); } / 参数校验非常,将校验失落败的所有非常组合成一条缺点信息 @param e 非常 @return 非常结果 / @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public ErrorResponse handleValidException(MethodArgumentNotValidException e) { log.error("参数绑定校验非常", e); return wrapperBindingResult(e.getBindingResult()); } / 包装绑定非常结果 @param bindingResult 绑定结果 @return 非常结果 / private ErrorResponse wrapperBindingResult(BindingResult bindingResult) { StringBuilder msg = new StringBuilder(); for (ObjectError error : bindingResult.getAllErrors()) { msg.append(", "); if (error instanceof FieldError) { msg.append(((FieldError) error).getField()).append(": "); } msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage()); } return new ErrorResponse(ArgumentResponseEnum.VALID_ERROR.getCode(), msg.substring(2)); } / 未定义非常 @param e 非常 @return 非常结果 / @ExceptionHandler(value = Exception.class) @ResponseBody public ErrorResponse handleException(Exception e) { log.error(e.getMessage(), e); if (ENV_PROD.equals(profile)) { // 当为生产环境, 不适宜把详细的非常信息展示给用户, 比如数据库非常信息. int code = CommonResponseEnum.SERVER_ERROR.getCode(); BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR); String message = getMessage(baseException); return new ErrorResponse(code, message); } return new ErrorResponse(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage()); } }复制代码

可以看到,上面将非常分成几类,实际上只有两大类,一类是ServletException、ServiceException,还记得上文提到的 按阶段分类 吗,即对应 进入Controller前的非常 和 Service 层非常;然后 ServiceException 再分成自定义非常、未知非常。
对应关系如下:

进入Controller前的非常: handleServletException、handleBindException、handleValidException自定义非常: handleBusinessException、handleBaseException未知非常: handleException

接下来分别对这几种非常处理器做详细解释。

非常处理器解释handleServletException

一个http要求,在到达Controller前,会对该要求的要求信息与目标掌握器信息做一系列校验。
这里大略说一下:NoHandlerFoundException:首先根据要求Url查找有没有对应的掌握器,若没有则会抛该非常,也便是大家非常熟习的404非常;

HttpRequestMethodNotSupportedException:若匹配到了(匹配结果是一个列表,不同的是http方法不同,如:Get、Post等),则考试测验将要求的http方法与列表的掌握器做匹配,若没有对应http方法的掌握器,则抛该非常;

HttpMediaTypeNotSupportedException:然后再对要求头与掌握器支持的做比较,比如content-type要求头,若掌握器的参数署名包含表明@RequestBody,但是要求的content-type要求头的值没有包含application/json,那么会抛该非常(当然,不止这种情形会抛这个非常);MissingPathVariableException:未检测到路径参数。
比如url为:/licence/{licenceId},参数署名包含@PathVariable("licenceId"),当要求的url为/licence,在没有明确定义url为/licence的情形下,会被剖断为:短缺路径参数;

MissingServletRequestParameterException:短缺要求参数。
比如定义了参数@RequestParam("licenceId") String licenceId,但发起要求时,未携带该参数,则会抛该非常;TypeMismatchException: 参数类型匹配失落败。
比如:吸收参数为Long型,但传入的值确是一个字符串,那么将会涌现类型转换失落败的情形,这时会抛该非常;

HttpMessageNotReadableException:与上面的HttpMediaTypeNotSupportedException举的例子完备相反,即要求头携带了"content-type: application/json;charset=UTF-8",但吸收参数却没有添加表明@RequestBody,或者要求体携带的 json 串反序列化成 pojo 的过程中失落败了,也会抛该非常;HttpMessageNotWritableException:返回的 pojo 在序列化成 json 过程失落败了,那么抛该非常;

handleBindException

参数校验非常,后文详细解释。

handleValidException

参数校验非常,后文详细解释。

handleBusinessException、handleBaseException

处理自定义的业务非常,只是handleBaseException处理的是除了 BusinessException 意外的所有业务非常。
就目前来看,这2个是可以合并成一个的。

handleException

处理所有未知的非常,比如操作数据库失落败的非常。

注:上面的handleServletException、handleException 这两个处理器,返回的非常信息,不同环境返回的可能不一样,以为这些非常信息都是框架自带的非常信息,一样平常都是英文的,不太好直接展示给用户看,以是统一返回SERVER_ERROR代表的非常信息。

异于凡人的404

上文提到,当要求没有匹配到掌握器的情形下,会抛出NoHandlerFoundException非常,但实在默认情形下不是这样,默认情形下会涌现类似如下页面:

Whitelabel Error Page这个页面是如何涌现的呢?实际上,当涌现404的时候,默认是不抛非常的,而是 forward跳转到/error掌握器,spring也供应了默认的error掌握器,如下:

那么,如何让404也抛出非常呢,只需在properties文件中加入如下配置即可:

spring.mvc.throw-exception-if-no-handler-found=truespring.resources.add-mappings=false复制代码

如此,就可以非常处理器中捕获它了,然后前端只要捕获到特定的状态码,立即跳转到404页面即可捕获404对应的非常

统一返回结果

在验证统一非常处理器之前,顺便说一下统一返回结果。
说白了,实在是统一一下返回结果的数据构造。
code、message 是所有返回结果中必有的字段,而当须要返回数据时,则须要另一个字段 data 来表示。
以是首先定义一个 BaseResponse 来作为所有返回结果的基类;

然后定义一个通用返回结果类CommonResponse,继续 BaseResponse,而且多了字段 data;

为了区分成功和失落败返回结果,于是再定义一个 ErrorResponse末了还有一种常见的返回结果,即返回的数据带有分页信息,由于这种接口比较常见,以是有必要单独定义一个返回结果类 QueryDataResponse,该类继续自 CommonResponse,只是把 data 字段的类型限定为 QueryDdata,QueryDdata中定义了分页信息相应的字段,即totalCount、pageNo、 pageSize、records。

个中比较常用的只有 CommonResponse 和 QueryDataResponse,但是名字又贼鬼去世长,何不定义2个名字超大略的类来替代呢?于是 R 和 QR 出身了,往后返回结果的时候只需这样写:new R<>(data)、new QR<>(queryData)。
所有的返回结果类的定义这里就不贴出来了

验证统一非常处理

由于这一套统一非常处理可以说是通用的,所有可以设计成一个 common包,往后每一个新项目/模块只需引入该包即可。
所以为了验证,须要新建一个项目,并引入该 common包。

紧张代码

下面是用于验证的紧张源码:

@Servicepublic class LicenceService extends ServiceImpl<LicenceMapper, Licence> { @Autowired private OrganizationClient organizationClient; / 查询{@link Licence} 详情 @param licenceId @return / public LicenceDTO queryDetail(Long licenceId) { Licence licence = this.getById(licenceId); checkNotNull(licence); OrganizationDTO org = ClientUtil.execute(() -> organizationClient.getOrganization(licence.getOrganizationId())); return toLicenceDTO(licence, org); } / 分页获取 @param licenceParam 分页查询参数 @return / public QueryData<SimpleLicenceDTO> getLicences(LicenceParam licenceParam) { String licenceType = licenceParam.getLicenceType(); LicenceTypeEnum licenceTypeEnum = LicenceTypeEnum.parseOfNullable(licenceType); // 断言, 非空 ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(licenceTypeEnum); LambdaQueryWrapper<Licence> wrapper = new LambdaQueryWrapper<>(); wrapper.eq(Licence::getLicenceType, licenceType); IPage<Licence> page = this.page(new QueryPage<>(licenceParam), wrapper); return new QueryData<>(page, this::toSimpleLicenceDTO); } / 新增{@link Licence} @param request 要求体 @return / @Transactional(rollbackFor = Throwable.class) public LicenceAddRespData addLicence(LicenceAddRequest request) { Licence licence = new Licence(); licence.setOrganizationId(request.getOrganizationId()); licence.setLicenceType(request.getLicenceType()); licence.setProductName(request.getProductName()); licence.setLicenceMax(request.getLicenceMax()); licence.setLicenceAllocated(request.getLicenceAllocated()); licence.setComment(request.getComment()); this.save(licence); return new LicenceAddRespData(licence.getLicenceId()); } / entity -> simple dto @param licence {@link Licence} entity @return {@link SimpleLicenceDTO} / private SimpleLicenceDTO toSimpleLicenceDTO(Licence licence) { // 省略 } / entity -> dto @param licence {@link Licence} entity @param org {@link OrganizationDTO} @return {@link LicenceDTO} / private LicenceDTO toLicenceDTO(Licence licence, OrganizationDTO org) { // 省略 } / 校验{@link Licence}存在 @param licence / private void checkNotNull(Licence licence) { ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence); }}复制代码

PS: 这里利用的DAO框架是mybatis-plus。

启动时,自动插入的数据为:

-- licenceINSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)VALUES (1, 1, 'user','CustomerPro', 100,5);INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)VALUES (2, 1, 'user','suitability-plus', 200,189);INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)VALUES (3, 2, 'user','HR-PowerSuite', 100,4);INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)VALUES (4, 2, 'core-prod','WildCat Application Gateway', 16,16);-- organizationsINSERT INTO organization (id, name, contact_name, contact_email, contact_phone)VALUES (1, 'customer-crm-co', 'Mark Balster', 'mark.balster@custcrmco.com', '823-555-1212');INSERT INTO organization (id, name, contact_name, contact_email, contact_phone)VALUES (2, 'HR-PowerSuite', 'Doug Drewry','doug.drewry@hr.com', '920-555-1212');复制代码开始验证捕获自定义非常

1. 获取不存在的 licence 详情:http://localhost:10000/licence/5。
成功相应的要求:licenceId=1

考验非空

捕获 Licence not found 非常

Licence not found

2. 根据不存在的 licence type 获取 licence 列表:http://localhost:10000/licence/list?licenceType=ddd。
可选的 licence type 为:user、core-prod 。

校验非空

捕获 Bad licence type 非常

Bad licence type

捕获进入 Controller 前的非常

1. 访问不存在的接口:http://localhost:10000/licence/list/ddd

捕获404非常

2. http 方法不支持:http://localhost:10000/licencePostMapping

捕获 Request method not supported 非常

Request method not supported

3. 校验非常1:http://localhost:10000/licence/list?licenceType=getLicences

LicenceParam

捕获参数绑定校验非常

licence type cannot be empty

4. 校验非常2:post 要求,这里利用postman仿照。

addLicence

LicenceAddRequest

要求url即结果

捕获参数绑定校验非常

注:由于参数绑定校验非常的非常信息的获取办法与其它非常不一样,以是才把这2种情形的非常从 进入 Controller 前的非常 单独拆出来,下面是非常信息的网络逻辑:非常信息的网络

捕获未知非常

假设我们现在随便对 Licence 新增一个字段 test,但不修正数据库表构造,然后访问:http://localhost:10000/licence/1。
增加test字段

捕获数据库非常

Error querying database

小结

可以看到,测试的非常都能够被捕获,然后以 code、message 的形式返回。
每一个项目/模块,在定义业务非常的时候,只需定义一个列举类,然后实现接口 BusinessExceptionAssert,末了为每一种业务非常定义对应的列举实例即可,而不用定义许多非常类。
利用的时候也很方便,用法类似断言。

扩展

在生产环境,若捕获到 未知非常 或者 ServletException,由于都是一长串的非常信息,若直接展示给用户看,显得不足专业,于是,我们可以这样做:当检测到当前环境是生产环境,那么直接返回 "网络非常"。
生产环境返回“网络非常”

可以通过以下办法修合法前环境:

修合法前环境为生产环境

总结

利用 断言 和 列举类 相结合的办法,再合营统一非常处理,基本大部分的非常都能够被捕获。
为什么说大部分非常,由于当引入 spring cloud security 后,还会有认证/授权非常,网关的做事降级非常、跨模块调用非常、远程调用第三方做事非常等,这些非常的捕获办法与本文先容的不太一样,不过限于篇幅,这里不做详细解释,往后会有单独的文章先容。
其余,当须要考虑国际化的时候,捕获非常后的非常信息一样平常不能直接返回,须要转换成对应的措辞,不过本文已考虑到了这个,获取消息的时候已经做了国际化映射,逻辑如下:

获取国际化末了总结,全局非常属于老成长谈的话题,希望这次通过手机的项目对大家有点辅导性的学习。
大家根据实际情形自行修正。
也可以采取以下的jsonResult工具的办法进行处理,也贴出来代码.

@Slf4j@RestControllerAdvicepublic class GlobalExceptionHandler { / 没有登录 @param request @param response @param e @return / @ExceptionHandler(NoLoginException.class) public Object noLoginExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][noLoginExceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.NO_LOGIN); jsonResult.setMessage("用户登录失落效或者登录超时,请先登录"); return jsonResult; } / 业务非常 @param request @param response @param e @return / @ExceptionHandler(ServiceException.class) public Object businessExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][businessExceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("业务非常,请联系管理员"); return jsonResult; } / 全局非常处理 @param request @param response @param e @return / @ExceptionHandler(Exception.class) public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][exceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("系统缺点,请联系管理员"); return jsonResult; }}复制代码

作者:TopJavaer链接:https://juejin.im/post/5ed7a03f518825433c13ae47

标签:

相关文章

执业药师试卷代码解码药师职业发展之路

执业药师在药品质量管理、用药安全等方面发挥着越来越重要的作用。而执业药师考试,作为进入药师行业的重要门槛,其试卷代码更是成为了药师...

PHP教程 2025-02-18 阅读0 评论0

心灵代码主题曲唤醒灵魂深处的共鸣

音乐,作为一种独特的艺术形式,自古以来就承载着人类情感的表达与传递。心灵代码主题曲,以其独特的旋律和歌词,唤醒了无数人的灵魂深处,...

PHP教程 2025-02-18 阅读0 评论0

探寻福建各市车牌代码背后的文化内涵

福建省,地处我国东南沿海,拥有悠久的历史和丰富的文化底蕴。在这片充满魅力的土地上,诞生了许多具有代表性的城市,每个城市都有自己独特...

PHP教程 2025-02-18 阅读0 评论0

探寻河北唐山历史与现代交融的城市之光

河北省唐山市,一座地处渤海之滨,拥有悠久历史和独特文化的城市。这里既是古丝绸之路的起点,也是中国近代工业的发源地。如今,唐山正以崭...

PHP教程 2025-02-18 阅读0 评论0