How I create an error handler (404, 500…) in Spring Boot/MVC

后端 未结 5 1806
终归单人心
终归单人心 2020-12-05 06:06

For some hours I\'m trying to create a custom global error handler in Spring Boot/MVC. I\'ve read a lot of articles and nothing.

That is my error class:

5条回答
  •  忘掉有多难
    2020-12-05 06:14

    Additional to @Arash You could add a new BaseController class that you can extends,that handles the conversion from exception to http response.

         import com.alexfrndz.pojo.ErrorResponse;
         import com.alexfrndz.pojo.Error;
         import com.alexfrndz.pojo.exceptions.NotFoundException;
         import org.springframework.http.HttpStatus;
         import org.springframework.http.ResponseEntity;
         import org.springframework.web.bind.annotation.ExceptionHandler;
         import org.springframework.web.bind.annotation.ResponseBody;
         import org.springframework.web.bind.annotation.ResponseStatus;
    
         import javax.persistence.NoResultException;
         import javax.servlet.http.HttpServletRequest;
         import java.util.List;
    
         @Slf4j
         public class BaseController {
    
        @ExceptionHandler(NoResultException.class)
        public ResponseEntity handleNoResultException(
                NoResultException nre) {
            log.error("> handleNoResultException");
            log.error("- NoResultException: ", nre);
            log.error("< handleNoResultException");
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
    
    
        @ExceptionHandler(Exception.class)
        public ResponseEntity handleException(Exception e) {
            log.error("> handleException");
            log.error("- Exception: ", e);
            log.error("< handleException");
            return new ResponseEntity(e,
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    
        @ExceptionHandler(NotFoundException.class)
        @ResponseStatus(value = HttpStatus.NOT_FOUND)
        @ResponseBody
        public ErrorResponse handleNotFoundError(HttpServletRequest req, NotFoundException exception) {
            List errors = Lists.newArrayList();
            errors.add(new Error(String.valueOf(exception.getCode()), exception.getMessage()));
            return new ErrorResponse(errors);
        }
       }
    

提交回复
热议问题