gpt4 book ai didi

java - Spring Boot 异常处理

转载 作者:行者123 更新时间:2023-11-29 04:46:17 24 4
gpt4 key购买 nike

我们正在为我们的应用程序使用 spring boot。当基于 Accept-Language header 调用 Rest 服务时,我试图在响应中返回本地化结果。例如,如果 Accept-Language header 是:zh,ja;q=0.8,en。因为我们支持,所以回复将使用中文。

但是如果 Accept-Language header 是:zh1,ja;q=0.8,en。然后我得到如下所示的内部服务器错误,因为它无法调用 @ExceptionHandler 我没有得到我喜欢的响应。以下是我得到的

{
"timestamp": 1462213062585,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.IllegalArgumentException",
"message": "java.lang.IllegalArgumentException: range=zh1",
"path": "/user/v1//paymentmethods/creditdebitcards"
}

相反,这是我想要抛出的,因为对于所有其他异常,我们处理并抛出类似的响应。

{
"operation": {
"result": "ERROR",
"errors": [
{
"code": "1000",
"message": "An unidentified exception has occurred.",
"field": ""
}
],
"requestTimeStampUtc": "2016-05-02T18:22:03.356Z",
"responseTimeStampUtc": "2016-05-02T18:22:03.359Z"
}
}

下面是我的类,如果标题错误(如 zh1,ja;q=0.8,en),则下面的解析方法会像上面一样抛出 500 错误。

public class SmartLocaleResolver extends AcceptHeaderLocaleResolver {

@Autowired
ExceptionHandling exceptionHandling;

@Autowired
MessageHandler messageHandler;

@Override
public Locale resolveLocale(HttpServletRequest request) {
try {
List<LanguageRange> list = Locale.LanguageRange.parse(request.getHeader("Accept-Language"));
if (!list.isEmpty()) {
for (LanguageRange s : list) {
if (ApplicationConstants.LOCALE.contains(s.getRange())) {
return Locale.forLanguageTag(s.getRange());
}
}
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e);
}
return request.getLocale();
}

下面是ExceptionHandler类

@EnableWebMvc
@ControllerAdvice
public class ExceptionHandling extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandling.class);

@Autowired
private MessageHandler messageHandler;

@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(value = { UnsupportedMediaTypeException.class, InvalidMediaTypeException.class })
public void unsupportedMediaTypeException() {

}

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = Exception.class)
public @ResponseBody OperationsErrorBean handleglobalException(final HttpServletRequest request,
final Exception ex) {
LOGGER.error("Unhandled Exception Occurred: ", ex);
return errorResponse("1000", messageHandler.localizeErrorMessage("error.1000"), "", request.getRequestURI(),
request.getAttribute("startTime").toString());

}
}

这是我的 ApplicationConfig.java 类

@Configuration
@ComponentScan("com.hsf")
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

@Value("${spring.application.name}")
String appName;

@Bean
public AlwaysSampler defaultSampler() {
return new AlwaysSampler();
}

@Override
public void addInterceptors(final InterceptorRegistry registry) {

if (StringUtils.isNotBlank(appName)) {
MDC.put("AppName", appName);

} else {
MDC.put("AppName", "APPNAME_MISSING");
}

registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/user/v1/**");
}

@Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}

@Bean
public DispatcherServlet dispatcherServlet() {
final DispatcherServlet servlet = new DispatcherServlet();
servlet.setDispatchOptionsRequest(true);
return servlet;
}

@Bean
public MessageSource messageSource() {
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:i18n/messages");
// If true, the key of the message will be displayed if the key is not
// found, instead of throwing an exception
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
// The value 0 means always reload the messages to be developer friendly
messageSource.setCacheSeconds(10);
return messageSource;
}

}

最佳答案

unsupportedMediaTypeException 方法的 @ExceptionHandler 注释不包含 IllegalArgumentException,而不是:

@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(value = { UnsupportedMediaTypeException.class,
InvalidMediaTypeException.class })
public void unsupportedMediaTypeException() { }

应该是:

@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(value = { UnsupportedMediaTypeException.class,
InvalidMediaTypeException.class, IllegalArgumentException.class })
public void unsupportedMediaTypeException() { }

此外,由于处理多种语言似乎是您的应用程序的要求之一,我建议为这种情况创建一个专用的 RuntimeException InvalidAcceptLanguageException 而不是使用通用的 IllegalArgumentException为此目的。

关于java - Spring Boot 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36989819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com