i try to display simple error massage for the unavailable resource of my service model by extending my class with RuntimeException but didn't display
TodoService Implementation
#Override
public String retrieveTodoStatusById(Long id) {
Optional<String> optionalTodo = Optional.ofNullable(todoRepository.findStatusById(id));
System.out.println("OptionalTodo " +optionalTodo );
String status = optionalTodo.orElseThrow(TodoNotFoundException::new);
return status;
}
TodoNotFoundException
package mang.io.todosrestapi.exceptionhandler;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
#ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Todo not available")
public class TodoNotFoundException extends RuntimeException{
public TodoNotFoundException(){
}
public TodoNotFoundException(String message){
super(message);
}
}
default error with no message is display
Every time i run the exception error message is not display
How can display the error message?
Try to add this line in your application.properties file:
server.error.include-message=always
Related
I have a RouteBuilder class that is using its own Processor. When running locally in Camel using Maven, it runs fine. However, when I try to use camel-k, it says it cannot find the package. Is there something I need to do?
MyProcessor
package com.test.processor;
import java.io.File;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.file.GenericFile;
public class MyProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
Message inMsg = exchange.getIn();
Object body = inMsg.getBody();
if (body instanceof File) {
System.out.println("Is a FILE");
} else {
System.out.println("Not a FILE");
}
if (body instanceof GenericFile) {
System.out.println("Is a GF for sure");
GenericFile gf = (GenericFile) body;
String fileName = gf.getFileName();
System.out.println("Filename: " + fileName);
} else {
System.out.println("NOT a GF");
}
}
}
Router
package com.javainuse.route;
import org.apache.camel.builder.RouteBuilder;
import com.test.processor.MyProcessor;
public class SimpleRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
// Transfer files from one another using a processor
from("file:C:/inputFolder?noop=true")
.process(new MyProcessor())
.to("file:C:/outputFolder")
.setBody().simple("Test")
.log("Test log");
}
}
I am using minikube and run the command:
kamel run SimpleRouteBuilder.java --dev
[1] Exception in thread "main" org.apache.camel.RuntimeCamelException: org.joor.ReflectException: Compilation error: /com/test/route/SimpleRouteBuilder.java:4: error: package com.test.processor does not exist
[1] import com.test.processor.MyProcessor;
This is expected as camel-k does not know where to find the classes for your processor so you have two options:
embed the processor as inner class of your route
package your processor as a maven artifact (you can also use jitpack to avoid having to publish it to a maven repo while testing) and list it as any other dependency
I have a route, controller and view defined. When I do a get request for the home directory, which is "/", I am getting the error not found: value message. index.scala.html:2.
routes:
GET / controllers.HomeController.index(message: String, name: String)
GET /count controllers.CountController.count
GET /message controllers.AsyncController.message
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
index.scala.html:
#(name: String)
#(message: String)
#main("Welcome to Sparta") {
#welcome(message, style = "java")
}
HomeController.java:
package controllers;
import play.mvc.*;
import play.*;
import views.html.*;
import java.util.Date;
public class HomeController extends Controller {
public String name;
public String message;
public Result index(String name, String message) {
name = "TEST NAME";
message = "Test message";
return ok(name, "message: " + message);
}
}
Why is the error telling me I have not defined a value for message?
Your route and index method in the controller is not correct. If you are sending any parameters to the server, they come into the picture. Your URL does look like you are sending some parameter with it, so please remove parameters for the index method.
public Result index() {
name = "TEST NAME";
message = "Test message";
return ok(name, "message: " + message);
}
I'm trying to create an Error Resource that will show the exact same view for all 300-599 error codes. I've got it mostly working, with the exception of erroneous POST requests. The error I get is,
WARN [2017-09-06 23:56:51,475] org.eclipse.jetty.server.handler.ErrorHandler: Error page loop /error
It seems like something is off in my ErrorResource logic, but I can't seem to put my finger on it.
Here is the ErrorResource class...
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import com.project.views.ErrorView;
import java.net.URI;
#Path("/error/")
#Produces(MediaType.TEXT_HTML)
public class ErrorResource {
private String appName;
#Context
UriInfo uri;
public ErrorResource(String appName) {
this.appName = appName;
}
#POST
public Response errorPost() {
URI redirectUri = uri.getBaseUri();
return Response.seeOther(redirectUri).build();
}
#GET
public ErrorView error() {
return new ErrorView(appName);
}
#GET
#Path("/404/")
public Response error404() {
return Response.status(404).entity(new ErrorView(appName)).build();
}
}
The errorPost() function is what's giving me trouble. The idea was to do at 301 redirect back to the same page, ostensibly performing a GET request which gets caught by the regular error() function. My Application Class shows that I'm registering the error handler to catch all 300-599's...
public class WebAppApplication extends Application<WebAppConfiguration> {
public static void main(String[] args) throws Exception {
new WebAppApplication().run(args);
}
#Override
public void initialize(Bootstrap<WebAppConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/www", "/static"));
bootstrap.addBundle(new ViewBundle());
}
#Override
public void run(WebAppConfiguration config, Environment environment) {
/* Error Handling */
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(300,403,"/error");
errorHandler.addErrorPage(404, "/error/404");
errorHandler.addErrorPage(405,599,"/error");
/* Resources */
final HomeResource homeResource = new HomeResource(config.getAppName());
final ErrorResource errorResource = new ErrorResource(config.getAppName());
/* Environment Registration */
environment.getApplicationContext().setErrorHandler(errorHandler);
environment.jersey().register(homeResource);
}
}
And nothing too crazy in the Error view
public class ErrorView extends View {
private String appName;
public ErrorView(String appName) {
super("pageError.mustache");
this.appName = appName;
}
public String getAppName() {
return XSS.htmlEncode(appName);
}
}
The ErrorView mustache template only really contains a message, the navbar, and meta refresh HTML tag.
<meta http-equiv="refresh" content="10; url=/" />
But issuing an erronous POST request to the "/input/" (or any) endpoint throws that "page loop" error, and returns this in the browser...
Browser Screenshot:
Making this a catch-all error message would help to keep the code base clean, will be helpful to the user, and maintains the website branding even in a unexpected failure.
I appreciate any insight the community might have, and preemptive "thank you" for the advice!
I want to return a JSON response instead of HTML.
I dont know how to trap it.
For example i set the 'play.http.parser.maxMemoryBuffer' to 1MB, and if the request body will exceed 1 MB, it will return a JSON response but not HTML format saying that it is a bad response.
According to the documentation:
To switch from HTML to JSON response you can add this line to application.conf
play.http.errorHandler = play.http.JsonHttpErrorHandler
If you also want to customize the message, you should instead add this line to application.conf
play.http.errorHandler = "com.example.ErrorHandler"
Obviously, the line above, should point to your own implementation of the error handler, that could look like this:
package com.example
import play.http.HttpErrorHandler;
import play.mvc.*;
import play.mvc.Http.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Singleton;
#Singleton
public class ErrorHandler implements HttpErrorHandler {
public CompletionStage<Result> onClientError(RequestHeader request, int statusCode, String message) {
if (statusCode == 413) {
return CompletableFuture.completedFuture(Results.status(statusCode, "A client error occurred: " + message + " The payload size should be lower than 1Mb."));
} else {
return CompletableFuture.completedFuture(Results.status(statusCode, "A client error occurred: " + message));
}
}
public CompletionStage<Result> onServerError(RequestHeader request, Throwable exception) {
return CompletableFuture.completedFuture(
Results.internalServerError("A server error occurred: " + exception.getMessage()));
}
}
I am new to Spring Boot I am following this tutorial
https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate
All I have done is that downloaded this jar and built it and ran it on localhost:8080
My Application.java which is the main file is as follows:
package netgloo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My Main Controller is as follows:
package netgloo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class MainController {
#RequestMapping("/")
#ResponseBody
public String index() {
return "Proudly handcrafted by " +
"<a href='http://netgloo.com/en'>netgloo</a> :)";
}
}
My Users Controller is as follows:
package netgloo.controllers;
import netgloo.models.User;
import netgloo.models.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping(value="/user")
public class UserController {
#Autowired
private UserDao _userDao;
#RequestMapping(value="/delete")
#ResponseBody
public String delete(long id) {
try {
User user = new User(id);
_userDao.delete(user);
}
catch(Exception ex) {
return ex.getMessage();
}
return "User succesfully deleted!";
}
#RequestMapping(value="/get-by-email")
#ResponseBody
public String getByEmail(String email) {
String userId;
try {
User user = _userDao.getByEmail(email);
userId = String.valueOf(user.getId());
}
catch(Exception ex) {
return "User not found";
}
return "The user id is: " + userId;
}
#RequestMapping(value="/save")
#ResponseBody
public String create(String email, String name) {
try {
User user = new User(email, name);
_userDao.save(user);
}
catch(Exception ex) {
return ex.getMessage();
}
return "User succesfully saved!";
}
} // class UserController
When I type in localhost:8080 I see the message defined in the main controller.
When I type any of the other end points in the UserController e.g. localhost:8080/user or localhost:8080/get-by-email?email=a#gmail.com it throws a 404.
Please advise what I am missing in this code.
You are trying with wrong urls.
Try with these:
localhost:8080/user/save?email=a#gmail.com&name=a
localhost:8080/user/get-by-email?email=a#gmail.com
Since you are using a #RequestMapping("/user") annotation on the class UserController, the path "/user" is prefixed on all the request mappings in such class. See here for more info.