preventing or handle jax-rs bean validation exception - validation

is there a way to handle jax-rs validation exception, I mean to not the throwing exception, just sysout my string.
I use #Valid annotation in this way
public function name (#Valid DtoClassName dtoVariableName);
using resteasy 2 and wildfly 19.
I use mapper as previous answers here, but nothing work, it's throw the exception then call the mapper.
#Provider
public class ValidationExceptionMapper implements ExceptionMapper<javax.validation.ConstraintViolationException> {
public ValidationExceptionMapper() {
System.out.println("ValidationExceptionMapper");
// TODO Auto-generated constructor stub
}
#Override
public Response toResponse(ConstraintViolationException exception) {
// TODO Auto-generated method stub
return Response.status(Status.BAD_REQUEST).entity("HELLLO ERROR").build();
}
}

Related

Request validation with quarkus

I have a REST Enspoint
...
#GET
public Response read (#Valid Param parameters) {
}
...
How can I catch this Exception to handle this in Quarkus?
Is there a special Exceptionhandler available?
You can handle the exception by using:
#Provider
public class MyViolationExceptionMapper implements ExceptionMapper<ValidationException> {
#Override
public Response toResponse(ValidationException exception) {
// do something
}
}
You can draw inspiration for how to handle things by looking at the built-in exception mapper.

How to handle exception in controller method with controlleradvice being in place

I do have a Spring boot controller class and a corresponding ControllerAdvice class which has ExceptionHandlers to handle different exception.
My controller method calls a simple validation helper class to validate input fields which throws an exception if validation fails. Now if I don't put a try catch block in my controller it keeps complaining me that you have a method which has untangled exception even through the logic for handling validation exception is defined in controlleradvice class. Please suggest how do I solve it.
From the method of ValidationHelper class if you throw any Checked Exception then you need to use a try-catch block to call that method.
If you don't want then it's better to use any Custom Exception class which will extend the RuntimeException class and you throw that exception. Then you don't need to explicitly mention the throws as well as you don't need to have a try-catch block at the controller.
#RestController
#RequiredArgsConstructor
public class SampleController {
private final ValidationHelper validationHelper;
#ResponseStatus(HttpStatus.OK)
#GetMapping("/sample")
public String getRequest(#RequestParam String name) {
validationHelper.validate(name);
return "";
}
}
#Service
public class ValidationHelper {
public Boolean validate(String name) {
throw new CustomException("Validation Failed");
}
}
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}

Spring Exception handler - Handling multiple exceptions

Below is my ExceptionHandler method to handle different exceptions that can be thrown from service class.
#ExceptionHandler({ExceptionA.class, ExceptionB.class, ExceptionC.class})
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
#ResponseBody
public void handle(ExceptionA e) {
log.error("Exception occurred: {} {}", e.getMessage(), e);
}
When ExceptionA is thrown, everything works as expected. But when ExceptionB is thrown, it gives the error No suitable resolver for argument 0 of type 'ExceptionA'. I guess its because the method argument for handle method is Exception A (still I would expect the error message should say No resolver for Exception B).
What should be the method argument for handle method so that it can handle any of the 3 exceptions?
Note: All Exceptions are created by extending from RuntimeException.
You need a common base class as parameter type, e.g RuntimeException:
#ExceptionHandler({ExceptionA.class, ExceptionB.class, ExceptionC.class})
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
#ResponseBody
public void handle(RuntimeException e) {
log.error(e.getMessage(), e);
}
Make your own base class extending RuntimeException
public class HandledRuntimeException extends RuntimeException{
}
and extend this class from your exception class like,
public class ExceptionA extends HandledRuntimeException{
}
and finally, in your handle method, you can change as below
#ExceptionHandler({HandledRuntimeException.class})
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
#ResponseBody
public void handle(HandledRuntimeException e) {
log.error("Exception occurred: {} {}", e.getMessage(), e);
}

How to test exceptions handling in #ControllerAdvice

I currently have two ControllerAdvice in my application, I'm supposed to merge them into one.
But I need to test them before and after the merge, test the exception and the object that the controller return me.
I'm trying to make a jUnit test with Mockito but it seems impossible to test the exceptions without any context, without a controller, etc ...
Does anyone know how can I proceed to achieve what I'm trying to do ?
I also try to throw manually an exception but obviously it wasn't catched by the ControllerAdvice.
So basically here is what i'm trying to do:
Manually throw an exception
This exception is handled by my ControllerAdvice
Check the returned object (code & message)
Here is a sample of code I have:
#Before
public void setup() {
...
mockMvc = MockMvcBuilders.standaloneSetup(getController())
.setControllerAdvice(new GlobalControllerExceptionHandler())
.setCustomArgumentResolvers(resolver, resolver_0, resolver_1)
.setHandlerExceptionResolvers(exceptionResolver).build();
}
#Controller
#RequestMapping("/tests")
public static class RestProcessingExceptionThrowingController {
#RequestMapping(value = "/exception", method = GET)
public #ResponseBody String find() {
throw new EntityNotFoundException();
}
}
#Test
public void testHandleException() throws Exception {
mockMvc.perform(get("/tests/exception"))
.andExpect(new ResultMatcher() {
#Override
public void match(MvcResult result) throws Exception {
result.getResponse().getContentAsString().contains("global_error_test");
}
})
.andExpect(status().isNotFound());
}
I have the good status code at the end but it doesn't use my ControllerAdvice (I try with the debugger)
You can just call handler method directly
#ControllerAdvice
MyAdvice{
#ExceptionHandeler(listOfExxcetpions)
public ResponseEntity someOfMyExceptionsHandler(Exception e){
.....
}
}
and in test
MuTest{
private MyAdvice advice=new MyAdvice();
#Test
public void oneOfTests(){
Exception e=new SomeSortOfExceptionToTest();
resp=advice.someOfMyExceptionsHandler(e)
assertThat(resp).....dostuff;
}
}
If you want to test how spring integrates with your handlers - if your annotations are correct, ordering serialization etc - well that will be an integration test and you have to boot up test context - then you can throw exceptions directly from controller methods.

CXF - custom exception is not caught by CXF

I am developing a SOAP web service with CXF 2.3.3. I want to throw a custom exception when user has submitted wrong data. My exception class looks like this.
#WebFault(name="InvalidUserDataException", targetNamespace="http://foo.bar.com/")
#XmlAccessorType(XmlAccessType.FIELD)
public class InvalidUserDataException extends RuntimeException {
public InvalidUserDataException(){
super();
}
String validationErrors;
}
In my method Impl class I purposely throw this exception to see whether SoapFault exception is returned by CXF to client, but whatever I do to any of these classes results in same error: createNewUser has thrown exception, unwinding now.
Note that WSUserRegistration interface also declares itself that createNewUser method throws InvalidUserDataException.
public class WSUserRegistrationImpl implements WSUserRegistration {
#Autowired
IWSUserValidationProxy validationProxyImpl;
#Override
public int createNewUser(RegistrationInputProperty registrationInfo) throws InvalidUserDataException {
if (true) {
throw new InvalidUserDataException();
}
return 1;
}
}
My goal is to catch this exception from a SOAPFaultOutInterceptor and return a customized faultDetail.
How do I make CXF catch this error and return a SOAPFault object? Any ideas?
this would help you.
http://willemjiang.blogspot.com/2011/01/how-to-map-soap-fault-message-with.html

Resources