Spring Boot 中的自定义异常

     2023-02-27     141

关键词:

【中文标题】Spring Boot 中的自定义异常【英文标题】:Custom Exception in Sprin Boot 【发布时间】:2019-12-12 09:54:06 【问题描述】:

我在 SPRING BOOT 中编写了以下自定义错误处理程序

@RestControllerAdvice 
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler 

    @ExceptionHandler
   // @ResponseBody
    public ResponseEntity<CustomErrorResponse> customHandleNotFound(Exception ex, WebRequest request) 

        CustomErrorResponse errors = new CustomErrorResponse();
        errors.setTimestamp(LocalDateTime.now());
        errors.setError(ex.getMessage());
        errors.setStatus(HttpStatus.CONFLICT.value());
        errors.setErrorMsg(errors.getErrorMsg());

        return  ResponseEntity.ok(errors);

    

下面是我的代码控制器方法

@RestController
@RequestMapping(value="/api")
public class AppController 




   @Autowired
    private UserRepository userRepository;



      @RequestMapping(value="/home/id1" ,method=RequestMethod.PUT)
     @ResponseBody
      public String home(@PathVariable("id1") Long idValue,    @RequestBody @Valid Student s)
    

         System.out.println( " idValue is  "  + idValue);

        System.out.println( " Student -->" + s.getName()  + " -- "  + s.getId());


      return    "job done";

    



      @RequestMapping("/foos")
    //  @ResponseBody
      public String getFoos(@RequestParam(value="t1",required=true)  String id)  

          int i =1/0;

          System.out.println(" id is " + i++);
            return "ID: " + id + "  status: Success";
      

异常处理程序对于方法 getFoos() 工作正常 当它遇到 1/0 时,我在 POSTMAN 中得到了预期的输出


    "timestamp": "2019-08-04 11:24:22",
    "status": 409,
    "error": "/ by zero",
    "errorMsg": "ERROR-msg"

但是在我的 home() 方法中,我故意将 Student 对象设为无效,并且在 POSTMAN 中没有收到错误消息,而只是在 Eclipse 控制台中。 为什么?

我收到此消息。那么当 Student 对象无效时,我该如何启动 CustomGlobalExceptionHandler

2019-08-04 23:25:57.551 警告 9652 --- [nio-8080-exec-6] .m.m.a.ExceptionHandlerExceptionResolver :已解决 [org.springframework.http.converter.HttpMessageNotReadableException: 缺少所需的请求正文:public java.lang.String com.example.hibernatemapping.controller.AppController.home(java.lang.Long,com.example.hibernatemapping.domain.Student)]

【问题讨论】:

添加@ExceptionHandler(HttpMessageNotReadableException.class, Exception.class) 添加后我的服务器现在甚至都没有启动 为 [class org.springframework.http.converter.HttpMessageNotReadableException] 映射的模糊 @ExceptionHandler 方法:public org.springframework.http.ResponseEntity com.example.hibernatemapping.exception.CustomGlobalExceptionHandler.customHandleNotFound(java. lang.Exception,org.springframework.web.context.request.WebRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception, org.springframework.web.context.request.WebRequest) 好的,所以只是@ExceptionHandler(Exception.class) 它不适用于 home() 方法 【参考方案1】:

嗯,有很多话要说。

首先,异常处理程序将异常类作为参数,它允许您在控制器方法中抛出的异常类之后返回其他错误。

您编写的那个捕获所有异常并返回相同的错误模型,这不是一个正确的想法。正确的做法是编写一个扩展 Exception 的抽象类 AbstractMyAppException,然后为您遇到的每个错误情况实现一个扩展它的新类。

然后,添加两个@ExceptionHandler

AbstractMyAppException 类上的一个绑定,它返回您的应用生成的所有错误 Exception 类上的一个绑定返回所有其他不应发生的错误。

对于您的情况,您似乎正在使用 Spring Validation(您正在使用 @Valid 注释)。所以请确保您已关注this tutorial。

然后,您的问题是关于捕获验证错误以在学生无效时显示自定义消息。然后检查this thread。

【讨论】:

它没有回答我的问题。这个答案让我很困惑 那么对不起,你的问题不是很清楚……你能具体说明你想知道什么吗? 我希望 home() 返回错误与 ` "timestamp": "2019-08-04 11:24:22", "status": 409, "error ": "/ by zero", "errorMsg": "ERROR-msg" ` 这是我的 CustomErrorResponse 类字段【参考方案2】:

我通过在我的 ControllerAdvice 中添加以下内容来解决它我只需更改代码以将错误映射到我的自定义 Pojo 类 CustomErrorResponse

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status, WebRequest request) 

        Map<String, Object> body = new LinkedHashMap<>();
        body.put("timestamp", new Date());
        body.put("status", status.value());

        //Get all errors
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());

        body.put("errors", errors);

         System.out.println( " erro here ");
        return new ResponseEntity<>(body, headers, status);



【讨论】:

Spring Boot JPA中的自定义查询问题

】SpringBootJPA中的自定义查询问题【英文标题】:ProblemwithcustomQueryinSpringbootJPA【发布时间】:2020-07-0502:06:49【问题描述】:我正在尝试按范围计算记录数,但在运行服务时出现错误:Causedby:org.hibernate.hql.internal.ast.QuerySyntaxException:... 查看详情

带有spring-boot的自定义sql中的Liquibase参数

】带有spring-boot的自定义sql中的Liquibase参数【英文标题】:Liquibaseparametersincustomsqlwithspring-boot【发布时间】:2019-04-1910:16:51【问题描述】:我在jdk11上有一个spring-boot应用程序,使用maven,具有以下liquibase依赖项:<dependency><... 查看详情

Spring Boot - 实体中的自定义类字段

】SpringBoot-实体中的自定义类字段【英文标题】:SpringBoot-customclassfieldinentity【发布时间】:2017-11-2620:15:20【问题描述】:我有2个自定义类,OzBakim和GunlukEtkinlik。这些类不是实体。我需要在实体中使用这些类。但我得到一个错误... 查看详情

Spring MVC(或 Spring Boot)。针对安全相关异常(例如 401 Unauthorized 或 403 Forbidden)的自定义 JSON 响应)

】SpringMVC(或SpringBoot)。针对安全相关异常(例如401Unauthorized或403Forbidden)的自定义JSON响应)【英文标题】:SpringMVC(orSpringBoot).CustomJSONresponseforsecurityrelatedexceptionslike401Unauthorizedor403Forbidden)【发布时间】:2018-05-2015:58:03【问题... 查看详情

Spring boot - Application.properties 中的自定义变量

】Springboot-Application.properties中的自定义变量【英文标题】:Springboot-customvariablesinApplication.properties【发布时间】:2015-11-1014:05:59【问题描述】:我有一个使用restfulapi的springboot客户端。我可以使用application.properties中的任何密钥条... 查看详情

处理 Spring Boot 资源服务器中的安全异常

】处理SpringBoot资源服务器中的安全异常【英文标题】:HandleSecurityexceptionsinSpringBootResourceServer【发布时间】:2017-04-2916:03:40【问题描述】:如何让我的自定义ResponseEntityExceptionHandler或OAuth2ExceptionRenderer在纯资源服务器上处理Spring... 查看详情

Spring Boot,MongoDB,Pageable,按对象中的自定义方法排序

】SpringBoot,MongoDB,Pageable,按对象中的自定义方法排序【英文标题】:SpringBoot,MongoDB,Pageable,sortbyacustommethodintheobject【发布时间】:2020-04-2214:27:46【问题描述】:比如说我有以下设置,这样的模型:publicclassPost@IdprivateStringid;privat... 查看详情

无法从 Spring Boot 应用程序中的自定义 yml 文件加载配置

】无法从SpringBoot应用程序中的自定义yml文件加载配置【英文标题】:Cannotloadconfigfromcustomymlfileinspringbootapplication【发布时间】:2017-11-1608:30:55【问题描述】:我正在从我的SpringBoot服务中的application.yml加载自定义配置。我已经通... 查看详情

Rest Service 中的 Spring Boot 自定义异常

】RestService中的SpringBoot自定义异常【英文标题】:SpringBootcustomexceptionwithinanRestService【发布时间】:2014-12-1611:51:31【问题描述】:我在基于SpringBoot的Rest服务中定义了一个全局异常处理:@ControllerAdvicepublicclassGlobalExceptionControllerpri... 查看详情

抛出异常时,Spring Boot 不显示自定义错误

】抛出异常时,SpringBoot不显示自定义错误【英文标题】:Springbootdoesnotshowcustomerrorwhenexceptionisthrown【发布时间】:2020-03-1518:30:00【问题描述】:我对Java/Spring领域相当陌生,我正在尝试在我的SpringBoot应用程序中使用@ControllerAdvice... 查看详情

尝试在spring boot中将env变量读取到不在application.property中的自定义属性文件

】尝试在springboot中将env变量读取到不在application.property中的自定义属性文件【英文标题】:tryingtoreadenvvariablestocustompropertiesfilenotinapplication.propertyinspringboot【发布时间】:2021-01-0510:45:27【问题描述】:我正在尝试从custom.properties... 查看详情

用于指定分发管理的自定义 spring boot 启动器

】用于指定分发管理的自定义springboot启动器【英文标题】:Customspringbootstarterforspecifyingdistributionmanagement【发布时间】:2017-01-0801:23:22【问题描述】:我们有一个SpringBoot应用程序,它的父级定义为spring-boot-starter-parent。但是在我... 查看详情

Spring Boot 异常自定义处理 - 意外的 HTTP 状态

】SpringBoot异常自定义处理-意外的HTTP状态【英文标题】:SpringbootExceptioncustomhandling-UnexpectedHTTPstatus【发布时间】:2019-02-2502:14:41【问题描述】:我正在尝试在我的SpringBoot应用程序中实现一些自定义异常处理程序,这些处理程序... 查看详情

带有 Java/Spring Boot 的 GraphQL 无法从传递的查询中选择定义为在模式中的字段上定义的自定义指令

】带有Java/SpringBoot的GraphQL无法从传递的查询中选择定义为在模式中的字段上定义的自定义指令【英文标题】:GraphQLwithJava/SpringbootunabletopickcustomdirectivedefinedasonFieldinschemafrompassedquery【发布时间】:2021-08-1120:42:52【问题描述】:已... 查看详情

缺少资源 bean:Spring Boot webflux 自定义全局异常处理程序

】缺少资源bean:SpringBootwebflux自定义全局异常处理程序【英文标题】:MissingResourcesbean:Springbootweb-fluxCustomGlobalExceptionhandler【发布时间】:2022-01-1503:47:19【问题描述】:我正在尝试通过扩展AbstractErrorWebExceptionHandler来实现我的自定... 查看详情

java - 如何在spring boot java中编写一个函数来处理JPA存储库中的自定义查询?

】java-如何在springbootjava中编写一个函数来处理JPA存储库中的自定义查询?【英文标题】:HowtowriteafunctiontohandlecustomqueryinJPArepositoryinspringbootjava?【发布时间】:2019-09-0312:14:14【问题描述】:基本上,我使用SpringBoot在服务器端托管... 查看详情

在 Spring Boot 中的异常处理期间保留自定义 MDC 属性

】在SpringBoot中的异常处理期间保留自定义MDC属性【英文标题】:PreservecustomMDCattributesduringexception-handlinginSpringBoot【发布时间】:2019-08-0410:12:01【问题描述】:短版(有足够的细节)如何保留在javax.servlet.Filter实现的doFilter()方法... 查看详情

如何处理 grails spring-security-rest 插件中的自定义身份验证异常?

】如何处理grailsspring-security-rest插件中的自定义身份验证异常?【英文标题】:HowdoIhandleacustomauthenticationexceptioningrailsspring-security-restplugin?【发布时间】:2017-03-0620:24:19【问题描述】:我正在使用带有spring-security-rest插件的Grails。... 查看详情