当前位置: 首页 > 科技观察

为你的Springboot项目定制一个通用异常

时间:2023-03-22 13:09:08 科技观察

前言我们的项目通常是一个比较大的项目,包括各种服务。如果每个服务以不同的方式返回异常信息,在排错的时候就会很乱。如果我们定义一个标准的异常处理系统。并用于所有服务。这样在开发的时候可以快速定位。该页面也将更简单、更直观。本文开发环境基于springboot2.4,IDE环境为IDEA。这是最简单的异常情况之一。逐渐过渡到完全自定义您自己的异常。案例:Springboot查询数据库数据,发现返回值为null,抛出异常。OK,基于这个思路,我们来看看实现思路。一、简单案例代码实现1、新建一个Springboot应用2、新建一个dao包。创建一个User类比较简单。代码如下:publicclassUser{privateintid;privateStringname;publicUser(){}publicUser(intid,Stringname){this.id=id;this.name=name;}//getter和setter方法//toString方法}3.新建一个服务包,创建UserService@ServicepublicclassUserService{publicUserfindOne(intid){//应该是从数据库中查询到User,但是数据库没有returnnull;}}由于演示是异常情况,所以没有真正实现对数据库的增删改查操作。调用findOne方法时,直接返回null即可。4.新建controller包,创建UserController类@RestControllerpublicclassUserController{@AutowiredprivateUserServiceservice;@GetMapping("/users/{id}")publicUserretriveUser(@PathVariableintid)throwsUserNotFoundException{Useruser=service.findOne(id);if(user==null)thrownewUserNotFoundException("id:"+id);returnuser;}}这里自定义了一个异常UserNotFoundException。一旦在查询数据库的时候发现返回值为null,就会直接抛出这个异常。5.在controller包下创建UserNotFoundException类publicclassUserNotFoundExceptionextendsRuntimeException{publicUserNotFoundException(Stringmessage){super(message);System.out.println("Theexceptionmessageis:"+message);}}6.Postman测试在此时间会发现服务器代码抛出错误。如果没有找到我们的资源,我们不能提示内部服务器错误。现在为抛出的异常做一个处理程序。7、异常处理@ResponseStatus(HttpStatus.NOT_FOUND)publicclassUserNotFoundExceptionextendsRuntimeException{publicUserNotFoundException(Stringmessage){super(message);System.out.println("异常信息为:"+message);}}我们会在@ResponseStatus中添加注解生成状态:404未找到。当然还有其他州。这个可以根据自己的需要退货。当我们使用HttpStatus.NOT_FOUND用户访问时,一旦抛出异常,就会显示404错误。如果切换到其他状态,将显示其他信息。8.重新测试SpringBoot和SpringMVC框架的结合提供了错误处理。一些默认的异常处理已在内部自动配置。因此,为开发中的所有服务配置一致的异常消息非常重要。2.一般异常处理1.添加依赖org.springframeworkspring-webmvc5.3.22.创建异常返回实体类ExceptionResponse这个类的作用就是在出现异常的时候我们要显示的信息。publicclassExceptionResponse{privateDatetimestamp;privateStringmessage;privateStringdetail;publicExceptionResponse(){}publicExceptionResponse(Datetimestamp,Stringmessage,Stringdetail){this.timestamp=timestamp;this.message=message;this.detail=urdetail;}publicDategetTimestampnage()(Stringret){returnmessage;}publicStringgetDetail(){returndetail;}}这里只需要实现getter方法,不实现setter方法。3.创建一个通用的异常处理类@ControllerAdvice@RestControllerpublicclassCustomizedResponseEntityExceptionHandlerextendsResponseEntityExceptionHandler{//这个方法主要处理所有的异常信息@ExceptionHandler(Exception.class)publicfinalResponseEntityhandleAllExceptions(Exceptionex,WebRequest/我们在异常发生时输出的请求){/信息,这里封装在ExceptionResponseExceptionResponseexceptionResponse=newExceptionResponse(newDate(),ex.getMessage(),request.getDescription(false));returnnewResponseEntity(exceptionResponse,HttpStatus.INTERNAL_SERVER_ERROR);}//页面资源找不到时的异常@ExceptionHandler(UserNotFoundException.class)publicfinalResponseEntityhandleUserNotFoundExceptions(UserNotFoundExceptionex,WebRequestrequest){ExceptionResponseexceptionResponse=newExceptionResponse(newDate(),ex.getMessage(),request.getDescription(false));returnnewResponseEntity(exceptionResponse,HttpStatus.NOT_FOUND);}}非常简单的。里面有很多API,大家可以根据自己的需要自行查看。4.Postman测试一切正常。赶快为你的程序定制一个通用的异常处理器吧。本文转载自微信公众号“愚公要移山”,可关注下方二维码。转载本文请联系愚公移山公众号。