SpringBoot的国际化错误信息返回

定义一个处理核心类

I18nController.java

package com.ewe.core.i18n;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;

@Controller
public class I18nController {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(I18nController.class);

	private MessageSource messageSource;
	@Value("${spring.messages.basename}") 
	private String basename;

	@Value("${spring.messages.cache-seconds}") 
	private long cacheMillis;

	@Value("${spring.messages.encoding}") 
	private String encoding;
	/**
	 * 初始化
	 * @return
	 */
	private MessageSource initMessageSource() { 
		ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();
		LOGGER.info("baseName====>:" + this.basename); 
		messageSource.setBasename(basename); 
		messageSource.setDefaultEncoding(encoding); 
		messageSource.setCacheMillis(cacheMillis);
		return messageSource; 
	}
	/**
	 * 设置当前的返回信息
	 * @param request
	 * @param code
	 * @return
	 */
	public String getMessage(HttpServletRequest request,String code){
		if(messageSource==null){
			messageSource=initMessageSource();
		}
		String lauage=request.getHeader("Accept-Language");
		//默认没有就是请求地区的语言
		Locale locale=null;
		if(lauage==null){
			locale=request.getLocale();
		}
		else if("en-US".equals(lauage)){
			locale=Locale.ENGLISH;
		}	
		else if("zh-CN".equals(lauage)){
			locale=Locale.CHINA;
		}
		//其余的不正确的默认就是本地的语言
		else{
			locale=request.getLocale();
		}
		String result=null;
		try {
			result = messageSource.getMessage(code, null, locale);
		} catch (NoSuchMessageException e) {
			LOGGER.error("Cannot find the error message of internationalization, return the original error message.");
		}
		if(result==null){
			return code;
		}
		return result;
	}
}
application配置文件加入如下配置
#message-source
spring.messages.basename=i18n/messages
#-1 no expried
spring.messages.cache-seconds= -1
spring.messages.encoding=UTF-8
创建以上的message信息文件

messages_en.properties

NotFound=Not found information.
NotFoundUser=This user doesn't exist.
OperationError=Error operation !
SuccessOperation=Success operation !
Exist=This data already exists. 
ExistUser=This user name already exists !
NewPasswordError=The new password is inconsistent with the confirmation password!
SamePassword=Same old and new passwords!
LogoutSuccess=Logout success!
ErrorPassword=Original password error!
LoginError=User name or password incorrect.
UserNameNull= The user name can not be null.
EmailNull=The email can not be null.
PasswordNull=The password can not be null.
PhoneStandbyNull=The phoneStandby can not be null.
MatchPassword=The two passwords don't match. 
NewPasswordNull=The new password can not be null.
OldPasswordNull=The old password can not be null.
EmailIncorrect=The email is incorrect.
PhoneIncorrect=The phone is incorrect.
PhoneStandbyIncorrect=The standby phone is incorrect.
PhoneEmergencyIncorrect=The emergency phone is incorrect.
ExpiredToken=Expired or invalid JWT token.
AccessDenied=Access Denied.
TimeZoneError=Time zone error or nonexistence.
UserIdError=The user id is incorrect or empty.
NumberFormatException=Data conversion error.
DateFormatError=The date is not in the correct format.
DataNull=The data can not be null.
messages_zh_CN.properties

NotFound=\u6CA1\u6709\u67E5\u8BE2\u5230\u4FE1\u606F\u3002
NotFoundUser=\u5F53\u524D\u8FD9\u4E2A\u7528\u6237\u4E0D\u5B58\u5728\u3002
OperationError=\u64CD\u4F5C\u9519\u8BEF\uFF01
SuccessOperation=\u64CD\u4F5C\u6210\u529F\uFF01
Exist=\u5F53\u524D\u8FD9\u4E2A\u6570\u636E\u5DF2\u5B58\u5728\uFF01
ExistUser=\u7528\u6237\u540D\u5DF2\u5B58\u5728\uFF01
NewPasswordError=\u65B0\u5BC6\u7801\u548C\u65E7\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF01
SamePassword=\u65B0\u65E7\u5BC6\u7801\u4E00\u81F4\uFF01
LogoutSuccess=\u767B\u51FA\u6210\u529F\uFF01
ErrorPassword=\u539F\u5BC6\u7801\u9519\u8BEF\uFF01
LoginError=\u7528\u6237\u540D\u6216\u8005\u5BC6\u7801\u4E0D\u6B63\u786E\uFF01
UserNameNull= \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A\uFF01
EmailNull=\u90AE\u7BB1\u4E0D\u80FD\u4E3A\u7A7A\uFF01
PasswordNull=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A
PhoneStandbyNull=\u5907\u7528\u8054\u7CFB\u7535\u8BDD\u4E0D\u80FD\u4E3A\u7A7A\uFF01
MatchPassword=\u4FE9\u6B21\u8F93\u5165\u7684\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF01
NewPasswordNull=\u65B0\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A\uFF01
OldPasswordNull=\u65E7\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A\uFF01
EmailIncorrect=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
PhoneIncorrect=\u624B\u673A\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
PhoneStandbyIncorrect=\u5907\u7528\u7535\u8BDD\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
PhoneEmergencyIncorrect=\u7D27\u6025\u7535\u8BDD\u683C\u5F0F\u4E0D\u6B63\u786E
ExpiredToken=\u4EE4\u724C\u5DF2\u7ECF\u8FC7\u671F\uFF01
AccessDenied=\u62D2\u7EDD\u8BBF\u95EE\uFF01
TimeZoneError=\u65F6\u533A\u586B\u5199\u9519\u8BEF\u6216\u8005\u4E0D\u5B58\u5728\uFF01
UserIdError=\u7528\u6237\u7684\u7F16\u53F7\u4E0D\u6B63\u786E\u6216\u8005\u4E3A\u7A7A\uFF01
NumberFormatException=\u6570\u636E\u8F6C\u6362\u9519\u8BEF\uFF01
DateFormatError=\u65E5\u671F\u7684\u683C\u5F0F\u4E0D\u6B63\u786E\uFF01
ConfigError=\u6743\u9650\u914D\u7F6E\u6587\u4EF6\u914D\u7F6E\u51FA\u9519\uFF01
DataNull=\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A\uFF01

以上就配置好了 怎么调用呢?

	@Autowired
	private I18nController i18n;

然后再方法里面调用这个
//根据键值对获取信息
        try {
			messageFound=i18n.getMessage(request, messageFound);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			messageFound=e.getMessage();
			e.printStackTrace();
		}

可以参考我的异常信息处理

只能参考异常处理

package com.ewe.core.exception;

/**
 * 在过滤器中抛出的异常信息,比如404 400 401 403 
 */
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ewe.core.dto.ErrorDto;
import com.ewe.core.i18n.I18nController;
/**
 * 返回Rest错误信息
 *
 * @author will
 * @author qianyi
 * @since 1.0
 */

@RestController
public class GlobalExceptionHandler implements ErrorController {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(GlobalExceptionHandler.class);

	private static final String PATH = "/error";
	@Autowired
	private I18nController i18n;
	
	@Autowired
	private ErrorAttributes errorAttributes;

	@RequestMapping(value = { "${error.path:/error}" }, produces = { "text/html" })
	public ErrorDto errorHtml(HttpServletRequest request,HttpServletResponse response) throws IOException {
		return error(request, response);
	}

	@RequestMapping({ "${error.path:/error}" })
	@ResponseBody
	public ErrorDto error(HttpServletRequest request,
		HttpServletResponse response) throws IOException {
		ErrorDto info = new ErrorDto();
		Map<String,Object> errorAttributes = getErrorAttributes(request, true);
		// System.out.println(errorAttributes);
        Integer status=(Integer)errorAttributes.get("status");
        String path=(String)errorAttributes.get("path");
        String trace=(String)errorAttributes.get("trace");
        String exception=(String)errorAttributes.get("exception");
        String messageFound=(String)errorAttributes.get("message");
        if(messageFound.equalsIgnoreCase("No message available")){
        	messageFound="AccessDenied";
        }
        else if(messageFound.indexOf("Access Denied")!=-1){
        	status=401;
        	messageFound="AccessDenied";
        }
        else if(messageFound.indexOf("Unauthorized")!=-1){
        	status=401;
        }
        else if(messageFound.indexOf("Expired or invalid JWT token")!=-1){
        	status=401;
        	messageFound="ExpiredToken";
        }
        else if(messageFound.indexOf("NumberFormatException")!=-1){
        	messageFound="NumberFormatException";
        }
        else if(messageFound.indexOf("Can not")!=-1&&messageFound.indexOf("java.util.Date")!=-1){
        	messageFound="DateFormatError";
        }
    	//根据键值对获取信息
        try {
			messageFound=i18n.getMessage(request, messageFound);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			messageFound=e.getMessage();
			e.printStackTrace();
		}
        
        String allMessage="\nMessage:"+messageFound+".\n When request path:"+path+". Here produces an exception:" + exception + ".\nTrace:\n"+trace;
		// 打印异常信息:
		info.setCode(status);
		info.setMessage(lcaolGeMessage(messageFound));
		LOGGER.error(allMessage);
		return info;
	}
	/**
	 * 处理异常
	 */
	public String lcaolGeMessage(String messageString){
		if(messageString.indexOf(":")!=messageString.lastIndexOf(":")){
			messageString=messageString.substring(0,messageString.indexOf(":"))+". "+messageString.substring(messageString.indexOf(":")+1).substring(0,messageString.substring(messageString.indexOf(":")+1).indexOf(":"));
			
		}
		return messageString;
	}
	@Override
	public String getErrorPath() {
		return PATH;
	}
	/**
	 * 根据请求处理数据
	 * @param request
	 * @param includeStackTrace
	 * @return
	 */
	private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        
	  	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	  	//System.out.println(requestAttributes.get);
        return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
    }
}



  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值