Friday, 14 January 2022

Handle parameterized error messages using MessageFormat class

 In this post, I am going to explain how to beautify application error messages using MessageFormat class.

‘java.text.MessageFormat’ class provides a format method that takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

For example,

MessageFormat.format("successsful inserts : {0},\nfailed inserts: {1},\nprocessing time : {2} milliseconds", "29", "1", "1234")

Above snippet generates the below message.

successsful inserts : 29,
failed inserts: 1,
processing time : 1234 milliseconds

{0} is replaced with 29

{1} is replaced with 1

{2} is replaced with 1234

 

Find the below working application.

Define AppErrorCodes class.

AppErrorCodes.java

package com.sample.app.format;

import java.text.MessageFormat;

public enum AppErrorCodes {
	ENTITY_CREATED(201, "App-200-1", "Entity is created with id {0}"), BULK_INSERT(201, "App-201-1",
			"successsful inserts : {0},\nfailed inserts: {1},\nprocessing time : {2} milliseconds");

	private String errorCode;
	private String errorMessage;
	private int httpCode;

	AppErrorCodes(int httpCode, String errorCode, String errorMessage) {
		this.httpCode = httpCode;
		this.errorCode = errorCode;
		this.errorMessage = errorMessage;
	}

	public String getFormattedErrorMessage(String... params) {
		return MessageFormat.format(errorMessage, params);
	}
}

Define main application class.

App.java

package com.sample.app.format;

public class App {

	public static void main(String args[]) {
		String formattedMessage = AppErrorCodes.BULK_INSERT.getFormattedErrorMessage("29", "1", "1234");

		System.out.println(formattedMessage);
	}

}

Output

successsful inserts : 29,
failed inserts: 1,
processing time : 1234 milliseconds



You may like

Miscellaneous

No comments:

Post a Comment