简体   繁体   中英

Spring boot translate default exceptions

1 . What i want to do is set default message for @Size validation like this

   @Size(min = 8,max = 255,message = "{validation.size}")

I dont want to put this on every field, so im asking if there is any way of setting global translation of this message..

  1. I want to translate error messages that are comming from spring security like Forbidden, Access denied etc

I already tried putting spring security messages like these in messages.properties

ExceptionTranslationFilter.insufficientAuthentication=A Custom message
AbstractAccessDecisionManager.accessDenied=A Custom message

But doesnt seem to be working..

You'll need a class annotated with @RestControllerAdvice . Add methods there to capture relevant exceptions and you can translate them into your responses. Even mess with http status response codes too if you want.

@RestControllerAdvice
@Slf4j
public class MyControllerExceptionHandling {
  @ExceptionHandler(MethodArgumentNotValidException.class)

  @ResponseStatus(BAD_REQUEST)
  public MyErrorMessageDto handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {

    return MyErrorMessageDto
        .builder()
        .cause("Bad something something")
        .build();
  }

}

Look up exceptions like MethodArgumentNotValidException and ConstraintViolationException as you'll need to handle these (and others) depending on your controller validation.

NB: The JSON you return for errors is just as much a contract with your clients as the JSON you return for successes, so have a google and see what others have done (before you get locked into something you wish you'd done better!).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM