SpringBoot2로 Rest api 만들기(7) – MessageSource를 이용한 Exception 처리
This commit is contained in:
@@ -25,6 +25,7 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'io.springfox:springfox-swagger2:2.6.1'
|
||||
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
|
||||
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
runtimeOnly 'com.h2database:h2'
|
||||
runtimeOnly 'mysql:mysql-connector-java'
|
||||
|
||||
@@ -4,6 +4,8 @@ import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.model.response.CommonResult;
|
||||
import com.rest.api.service.ResponseService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
@@ -17,15 +19,25 @@ public class ExceptionAdvice {
|
||||
|
||||
private final ResponseService responseService;
|
||||
|
||||
// @ExceptionHandler(Exception.class)
|
||||
// @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
// protected CommonResult defaultException(HttpServletRequest request, Exception e) {
|
||||
// return responseService.getFailResult();
|
||||
// }
|
||||
private final MessageSource messageSource;
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("unKnown.code")), getMessage("unKnown.msg"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(CUserNotFoundException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
protected CommonResult userNotFoundException(HttpServletRequest request, CUserNotFoundException e) {
|
||||
return responseService.getFailResult();
|
||||
return responseService.getFailResult(Integer.valueOf(getMessage("userNotFound.code")), getMessage("userNotFound.msg"));
|
||||
}
|
||||
|
||||
private String getMessage(String code) {
|
||||
return getMessage(code, null);
|
||||
}
|
||||
|
||||
private String getMessage(String code, Object[] args) {
|
||||
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
|
||||
63
src/main/java/com/rest/api/config/MessageConfiguration.java
Normal file
63
src/main/java/com/rest/api/config/MessageConfiguration.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rakugakibox.util.YamlResourceBundle;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.MissingResourceException;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
@Configuration
|
||||
public class MessageConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Bean // 세션에 지역설정. default는 KOREAN = 'ko'
|
||||
public LocaleResolver localeResolver() {
|
||||
SessionLocaleResolver slr = new SessionLocaleResolver();
|
||||
slr.setDefaultLocale(Locale.KOREAN);
|
||||
return slr;
|
||||
}
|
||||
|
||||
@Bean // 지역설정을 변경하는 인터셉터. 요청시 파라미터에 lang 정보를 지정하면 언어가 변경됨.
|
||||
private LocaleChangeInterceptor localeChangeInterceptor() {
|
||||
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
|
||||
lci.setParamName("lang");
|
||||
return lci;
|
||||
}
|
||||
|
||||
@Override // 인터셉터를 시스템 레지스트리에 등록
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
}
|
||||
|
||||
@Bean // yml 파일을 참조하는 MessageSource 선언
|
||||
public MessageSource messageSource(
|
||||
@Value("${spring.messages.basename}") String basename,
|
||||
@Value("${spring.messages.encoding}") String encoding
|
||||
) {
|
||||
YamlMessageSource ms = new YamlMessageSource();
|
||||
ms.setBasename(basename);
|
||||
ms.setDefaultEncoding(encoding);
|
||||
ms.setAlwaysUseMessageFormat(true);
|
||||
ms.setUseCodeAsDefaultMessage(true);
|
||||
ms.setFallbackToSystemLocale(true);
|
||||
return ms;
|
||||
}
|
||||
|
||||
// locale 정보에 따라 다른 yml 파일을 읽도록 처리
|
||||
private static class YamlMessageSource extends ResourceBundleMessageSource {
|
||||
@Override
|
||||
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
|
||||
return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import io.swagger.annotations.ApiParam;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
@Api(tags = {"1. User"})
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@@ -31,9 +33,9 @@ public class UserController {
|
||||
|
||||
@ApiOperation(value = "회원 단건 조회", notes = "userId로 회원을 조회한다")
|
||||
@GetMapping(value = "/user/{userId}")
|
||||
public BasicResult<User> findUserById(@ApiParam(value = "회원ID", required = true) @RequestParam int userId) {
|
||||
public BasicResult<User> findUserById(@ApiParam(value = "회원ID", required = true) @PathVariable int userId,
|
||||
@ApiParam(value = "언어", defaultValue = "ko") @RequestParam String lang) {
|
||||
// 결과데이터가 단일건인경우 getBasicResult를 이용해서 결과를 출력한다.
|
||||
// return responseService.getBasicResult(userJpaRepo.findById(userId).orElse(null));
|
||||
return responseService.getBasicResult(userJpaRepo.findById(userId).orElseThrow(CUserNotFoundException::new));
|
||||
}
|
||||
|
||||
@@ -63,7 +65,7 @@ public class UserController {
|
||||
@ApiOperation(value = "회원 삭제", notes = "userId로 회원정보를 삭제한다")
|
||||
@DeleteMapping(value = "/user/{userId}")
|
||||
public CommonResult delete(
|
||||
@ApiParam(value = "회원ID", required = true) @RequestParam int userId) {
|
||||
@ApiParam(value = "회원ID", required = true) @PathVariable int userId) {
|
||||
userJpaRepo.deleteById(userId);
|
||||
// 성공 결과 정보만 필요한경우 getSuccessResult()를 이용하여 결과를 출력한다.
|
||||
return responseService.getSuccessResult();
|
||||
|
||||
@@ -52,11 +52,11 @@ public class ResponseService {
|
||||
return result;
|
||||
}
|
||||
// 실패 결과만 처리하는 메소드
|
||||
public CommonResult getFailResult() {
|
||||
public CommonResult getFailResult(int code, String msg) {
|
||||
CommonResult result = new CommonResult();
|
||||
result.setSuccess(false);
|
||||
result.setCode(CommonResponse.FAIL.getCode());
|
||||
result.setMsg(CommonResponse.FAIL.getMsg());
|
||||
result.setCode(code);
|
||||
result.setMsg(msg);
|
||||
return result;
|
||||
}
|
||||
// 결과 모델에 api 요청 성공 데이터를 세팅해주는 메소드
|
||||
|
||||
@@ -9,4 +9,7 @@ spring:
|
||||
jpa:
|
||||
database-platform: org.hibernate.dialect.H2Dialect
|
||||
#properties.hibernate.hbm2ddl.auto: none
|
||||
showSql: true
|
||||
showSql: true
|
||||
messages:
|
||||
basename: i18n/exception
|
||||
encoding: UTF-8
|
||||
6
src/main/resources/i18n/exception_en.yml
Normal file
6
src/main/resources/i18n/exception_en.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
unKnown:
|
||||
code: "-9999"
|
||||
msg: "An unknown error has occurred."
|
||||
userNotFound:
|
||||
code: "-1000"
|
||||
msg: "This member not exist"
|
||||
6
src/main/resources/i18n/exception_ko.yml
Normal file
6
src/main/resources/i18n/exception_ko.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
unKnown:
|
||||
code: "-9999"
|
||||
msg: "알수 없는 오류가 발생하였습니다."
|
||||
userNotFound:
|
||||
code: "-1000"
|
||||
msg: "존재하지 않는 회원입니다."
|
||||
Reference in New Issue
Block a user