Java Spring启动更改覆盖异常响应

Java Spring启动更改覆盖异常响应,java,spring,spring-boot,Java,Spring,Spring Boot,我正在尝试自定义异常响应并使用我自己的响应结构,我使用以下方式: @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody public ResponseEntity<String> handle(Exception e

我正在尝试自定义异常响应并使用我自己的响应结构,我使用以下方式:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler
{
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handle(Exception ex, HttpServletRequest request)
    {
...
    }
}

在这一点上我可能是错的,但对我来说,同时使用@ResponseStatus注释和自定义ErrorHandler是没有意义的。 注释应该使代码更易于理解,并避免使用此类处理程序


如果您真的想使用该处理程序,我建议删除注释并在每个异常中存储相应的状态代码(例如作为
最终静态属性)。

我们无法更改异常消息。但是,我们可以更改代码和类,并通过使用相同的代码和不同的消息重写相同的类来抛出一个新的类。

使用java反射机制,您可以这样做:

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handle(Exception ex, HttpServletRequest request) {
        if (ex instanceOf ExtendSubscriptionReminderNotExistException) {
            ResponseStatus status = ExtendSubscriptionReminderNotExistException.class.getAnnotation(ResponseStatus.class);
            return ResponseEntity.status(status.value()).body(ex.getMessage());
        }else{
            //if it's not ExtendSubscriptionReminderNotExistException, do sth different
        }
    }
@ExceptionHandler(RuntimeException.class)
@应答器
公共响应属性句柄(异常ex,HttpServletRequest){
if(ex-instanceOf ExtendSubscriptionMemberNotExistException){
ResponseStatus=ExtendSubscriptionReminderNotExistException.class.getAnnotation(ResponseStatus.class);
返回ResponseEntity.status(status.value()).body(例如getMessage());
}否则{
//如果它不是ExtendSubscriptionMemberNotExistException,请做一些不同的事情
}
}
下面是一篇关于如何阅读java注释的有用文章:


如果要覆盖ResponseStatusExceptionResolver,则应
扩展AbstractHandlerExceptionResolver
并实现自己的
doResolveException
,然后创建一个扩展
WebMVCCConfiguration Support
的配置并覆盖,然后spring将选择您自己的异常解析器,而不是默认的异常解析器。这背后的逻辑是。

是否需要从异常的注释中检索代码,并将其设置为
GlobalExceptionHandler#handle
中的响应代码?如果我可以覆盖ResponseStatusExceptionResolver,doResolveException就是我想要的方法,您可以通过使用try-catch(例如try{functioncall();}catch)来实现这一点(异常e){throw new MyException('new message');}如果我可以覆盖ResponseStatusExceptionResolver,doResolveException就是我想要的方法如果我可以覆盖ResponseStatusExceptionResolver,我想doResolveException就是我想要的方法你肯定可以覆盖ResponseStatusExceptionResolver,请参阅我上面更新的答案。
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handle(Exception ex, HttpServletRequest request) {
        if (ex instanceOf ExtendSubscriptionReminderNotExistException) {
            ResponseStatus status = ExtendSubscriptionReminderNotExistException.class.getAnnotation(ResponseStatus.class);
            return ResponseEntity.status(status.value()).body(ex.getMessage());
        }else{
            //if it's not ExtendSubscriptionReminderNotExistException, do sth different
        }
    }