【问题标题】:Spring rest application and exception localizationSpring Rest 应用和异常本地化
【发布时间】:2017-07-20 10:15:42
【问题描述】:

我正在开发一个以 restful 服务和 angularjs 作为前端的 spring boot 应用程序。应用程序必须支持多种语言。我遇到的问题之一是我的服务引发的业务异常。例如。我有一个图书服务可能会抛出这样的异常

if (book == null) {
        throw new ServiceException("The book you are looking for no longer exist");
}

本地化它们的最佳方法是什么?

【问题讨论】:

  • 显示一些代码。你到底想要达到什么目的。前端本地化消息?还是异常本地化。?
  • 是的,我说的是异常本地化。我稍微修改了这个问题。
  • 您可以使用代码引发异常,并将其转换为控制器层中的友好消息。 (通过注入MessageSource)。见docs.spring.io/spring/docs/current/spring-framework-reference/…
  • 您在寻找@ControllerAdvice吗?

标签: angularjs spring rest


【解决方案1】:

您必须使用 @RestControllerAdvice 将您的异常处理逻辑与您的业务代码分开。根据@ControllerAdvice 文档,在类中定义为@ControllerAdvice 的方法全局适用于所有控制器。 @RestControllerAdvice 只是一个方便类,等于 (@RestControllerAdvice = @ControllerAdvice + @ResponseBody)。请检查以下课程:

@RestControllerAdvice
public class GenericExceptionHandler {

    @Autowired
    private MessageSource messageSource;

    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<ErrorResponse> handle(ServiceException.class e, Locale locale) {

            String errorMessage = messageSource.getMessage(
                                "error.message", new Object[]{},locale);  

            ErrorResponse error = new ErrorResponse();
            error.setErrorCode(HttpStatus.BAD_REQUEST.value());
            error.setMessage(errorMessage);


            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
}

// other Custom Exception handlers

您的 ErrorResponse 是正常的 javabean,如下所示:

public class ErrorResponse{

private int errorCode;
private String message;

//getter and setter
}

您应该在配置中配置 MessageSoruce 以读取特定于语言环境的错误消息,如下所示:

@Configuration
public class MessageConfig {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("i18n/messages");
        source.setUseCodeAsDefaultMessage(true);
        return source;
    }
}

【讨论】:

    【解决方案2】:

    我想建议使用@ControllerAdvice and @ExceptionHandler

    您也可以使用@RestControllerAdvice、find example here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 2019-02-02
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多