Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs springrest应用程序和异常本地化_Angularjs_Spring_Rest - Fatal编程技术网

Angularjs springrest应用程序和异常本地化

Angularjs springrest应用程序和异常本地化,angularjs,spring,rest,Angularjs,Spring,Rest,我正在开发一个SpringBoot应用程序,使用restful服务和angularjs作为前端。应用程序必须支持多种语言。我遇到的问题之一是从我的服务中抛出的业务异常。我有一个图书服务,它可能会抛出这样的异常 if (book == null) { throw new ServiceException("The book you are looking for no longer exist"); } 将它们本地化的最佳方法是什么 我建议使用@ControllerAdvice和

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

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

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

我建议使用
@ControllerAdvice和@ExceptionHandler


您还可以使用@RestControllerAdvice,

您必须使用@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
您应该在配置中配置MessageSoruce以读取特定于语言环境的错误消息,如下所示:

public class ErrorResponse{

private int errorCode;
private String message;

//getter and setter
}
@Configuration
public class MessageConfig {

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

显示一些代码。你到底想达到什么目的。前端本地化消息?是的,我说的是异常本地化。我对这个问题做了一些修改。你可以抛出一个异常,并在控制器层将代码转换成友好的消息。(通过注入
MessageSource
)。看,你在找什么?