4、spring boot + Maven + Restful Exception异常跳转和自定义错误

  1. 错误html页面(会根据错误自动跳转到页面)
    在这里插入图片描述

  2. 如果报错运行时异常会跳转到500.html
    在这里插入图片描述

  3. 使用Restlet Client来测试
    返回内部默认处理结果

  4. 自定义UserNotExistException类

package com.imooc.exception;

public class UserNotExistException extends RuntimeException {

	/**
	 * 序列号
	 */
	private static final long serialVersionUID = 1L;
	
	private String id;
	
	public UserNotExistException(String id) {
		super("user not exist");
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	
}

  1. 加载错误类的注解类
package com.imooc.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.imooc.exception.UserNotExistException;

/**
 * 加载自定义错误
 * @author caijiajun
 * @date   2018年9月11日
 */
@ControllerAdvice
public class ControllerExceptionHandler {
	
	@ExceptionHandler(UserNotExistException.class)//加载自定义错误类
	@ResponseBody//返回json格式
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//表明注解的类型
	public Map<String, Object> handlerUserNotExistException(UserNotExistException ex) {
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}
	
}

  1. 模拟错误发生
	@GetMapping("/{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	public User getInfo(@PathVariable(name = "id") String id) {
	throw new UserNotExistException(id);
//		System.out.println("进入getInfo服务");
//		User user = new User();
//		user.setUsername("tom");
//		return user;
	}
  1. 用Restlet Client 测试
    返回对应存放在result的值
  2. @JsonView的用法
    @JsonView返回实体类中指定字段属性
    在这里插入图片描述
    控制controller
	@GetMapping
	//指定参数名称@RequestParam(value = "usename", required = false ,defaultValue = "tom")
	@JsonView(User.UserSimpleView.class)
	@ApiOperation(value = "用户查询服务")
	public List<User> query(UserQueryCondition condition,@PageableDefault(page = 2 ,size =17, sort = "asc") Pageable pageable) {
		//反射的一个tostring工具
		System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); 
		System.out.println(pageable.getPageSize());
		System.out.println(pageable.getPageNumber());
		System.out.println(pageable.getSort());
		List<User> users = new ArrayList<>();
		users.add(new User());
		users.add(new User());
		users.add(new User());
		users.add(new User());
		return users;
	}

9.用Restlet Client 测试
在这里插入图片描述
注意:子接口如果继承父接口,那么返回的字段也包括父接口上添加的字段

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值